youngtsai commited on
Commit
9e744f2
·
1 Parent(s): 6ef69da

def batch_update_cells(self, sheet_url: str, update_data: list[dict]) -> dict | None:

Browse files
Files changed (1) hide show
  1. sheet_service.py +41 -23
sheet_service.py CHANGED
@@ -391,9 +391,9 @@ class SheetService:
391
 
392
  Args:
393
  sheet_url (str): Google Sheet 的 URL。
394
- update_data (list[dict]): 一個字典列表,每個字典包含:
395
  'range' (str): 要更新的範圍 (例如 '工作表名!A1')
396
- 'value' (str): 要寫入的值
397
 
398
  Returns:
399
  dict | None: Google API 的返回結果,如果成功。否則返回 None。
@@ -409,44 +409,62 @@ class SheetService:
409
  logging.warning("沒有需要批次更新的資料。")
410
  return None
411
 
412
- # 確保 update_data 中的 range 包含 sheet_name
413
- # (調用此方法前應已獲取 sheet_name 並填入 range)
414
- # 例如 update_data = [{'range': '測試!F2', 'value': 'OO'}, ...]
415
-
416
  body = {
417
  'valueInputOption': 'USER_ENTERED', # 或者 'RAW'
418
  'data': []
419
  }
 
420
  for item in update_data:
421
- # 基本的範圍和值檢查
422
- if 'range' not in item or 'value' not in item:
423
- logging.warning(f"跳過格式錯誤的更新項目: {item}")
424
  continue
425
- if '!' not in item['range'] or len(item['range'].split('!')[1]) < 2: # 簡單檢查範圍格式
426
- logging.warning(f"跳過範圍格式可能錯誤的更新項目: {item['range']}")
 
 
427
  continue
428
 
 
429
  body['data'].append({
430
  'range': item['range'],
431
- 'values': [[item['value']]] # value 需要是二維列表
432
  })
 
433
 
434
- if not body['data']:
435
- logging.warning("沒有有效的資料可以進行批次更新。")
436
- return None
 
 
 
437
 
438
  try:
439
- logging.info(f"準備批次更新 Spreadsheet ID: {spreadsheet_id},共 {len(body['data'])} 個儲存格...")
 
 
440
  result = self.service.spreadsheets().values().batchUpdate(
441
  spreadsheetId=spreadsheet_id,
442
  body=body
443
  ).execute()
444
  total_updated = result.get('totalUpdatedCells', 0)
445
- logging.info(f"批次更新完成。共更新了 {total_updated} 個儲存格。")
446
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  except Exception as e:
448
- logging.error(f"批次更新儲存格時發生 API 錯誤: {e}")
449
- # from googleapiclient.errors import HttpError
450
- # if isinstance(e, HttpError):
451
- # logging.error(f"錯誤詳情: {e.content}")
452
- return None
 
391
 
392
  Args:
393
  sheet_url (str): Google Sheet 的 URL。
394
+ update_data (list[dict]): 一個字典列表,每個字典應包含:
395
  'range' (str): 要更新的範圍 (例如 '工作表名!A1')
396
+ 'values' (list[list[str]]): 要寫入的值 (二維列表, 例如 [['value1']])
397
 
398
  Returns:
399
  dict | None: Google API 的返回結果,如果成功。否則返回 None。
 
409
  logging.warning("沒有需要批次更新的資料。")
410
  return None
411
 
 
 
 
 
412
  body = {
413
  'valueInputOption': 'USER_ENTERED', # 或者 'RAW'
414
  'data': []
415
  }
416
+ valid_updates_count = 0 # 計算實際加入請求的數量
417
  for item in update_data:
418
+ # 修正 1: 檢查 'values' 而不是 'value',並檢查 'values' 是否為列表
419
+ if 'range' not in item or 'values' not in item or not isinstance(item['values'], list):
420
+ logging.warning(f"跳過格式錯誤的更新項目 (缺少 'range' 或 'values' 非列表): {item}")
421
  continue
422
+ # 修正 2: 稍微改進範圍檢查,確保 '!' 後面有內容
423
+ range_parts = item['range'].split('!', 1) # 最多分割一次
424
+ if len(range_parts) != 2 or not range_parts[0] or not range_parts[1]:
425
+ logging.warning(f"跳過範圍格式錯誤的更新項目 (格式應為 'SheetName!A1'): {item['range']}")
426
  continue
427
 
428
+ # 修正 3: 直接使用 item['values'],它本身就應該是二維列表
429
  body['data'].append({
430
  'range': item['range'],
431
+ 'values': item['values'] # 直接使用傳入的二維列表
432
  })
433
+ valid_updates_count += 1
434
 
435
+ # 修正 4: 根據實際加入請求的數量判斷是否繼續
436
+ if not body['data']: # 或者 if valid_updates_count == 0:
437
+ logging.warning("經過驗證後,沒有有效的資料可以進行批次更新。")
438
+ # 即使沒有資料,也返回一個表示「沒有執行」的狀態,而不是 None,避免呼叫方誤判
439
+ # 或者可以返回一個特定的物件或空字典來表示未執行
440
+ return {"totalUpdatedCells": 0, "replies": [], "message": "No valid data to update after validation."} # 返回模擬的回應
441
 
442
  try:
443
+ # logging.info(f"準備批次更新 Spreadsheet ID: {spreadsheet_id},共 {len(body['data'])} 個儲存格...")
444
+ # 使用 valid_updates_count 進行日誌記錄更準確
445
+ logging.info(f"準備批次更新 Spreadsheet ID: {spreadsheet_id},共 {valid_updates_count} 個有效儲存格...")
446
  result = self.service.spreadsheets().values().batchUpdate(
447
  spreadsheetId=spreadsheet_id,
448
  body=body
449
  ).execute()
450
  total_updated = result.get('totalUpdatedCells', 0)
451
+ logging.info(f"批次更新完成。API 回報共更新了 {total_updated} 個儲存格。")
452
+ # 可以在這裡比較 total_updated 和 valid_updates_count
453
+ if total_updated != valid_updates_count:
454
+ logging.warning(f"預期更新 {valid_updates_count} 個儲存格,但 API 回報更新了 {total_updated} 個。")
455
+ return result # 返回實際的 API 回應
456
+ except googleapiclient.errors.HttpError as error: # 更具體地捕獲 HttpError
457
+ error_details = error.resp.get('content', '{}')
458
+ try:
459
+ error_json = json.loads(error_details)
460
+ error_message = error_json.get('error', {}).get('message', str(error))
461
+ except json.JSONDecodeError:
462
+ error_message = str(error)
463
+ logging.error(f"批次更新儲存格時發生 API 錯誤 (ID: {spreadsheet_id}): {error_message}")
464
+ logging.error(f"錯誤詳情: {error.content.decode()}") # 打印詳細錯誤內容
465
+ return None # API 錯誤返回 None
466
  except Exception as e:
467
+ logging.error(f"批次更新儲存格時發生未知錯誤: {e}")
468
+ import traceback
469
+ traceback.print_exc()
470
+ return None # 其他錯誤返回 None