python读取单元格格式_使用Python(API v4)从Google表格中读取单元格格式

使用Python API v4从Google表格中获取单元格格式。遍历所有工作表,提取每个单元格的背景颜色和格式化值。将数据存储在dataset列表中,方便后续处理。示例展示了如何获取第一个范围的A1和D2单元格的颜色和值。
摘要由CSDN通过智能技术生成

dataset=[]default_bg={'red':1,'green':1,'blue':1}# all_data['sheets'] is a list of sheet resources (per the API spec.)forsheetinall_data['sheets']:# The sheet resource is a dict with keys determined by what we requested in fields# (i.e. properties (->sheetId, ->title), data)print('Sheet name is {title} with grid id {sheetId}'.format_map(sheet["properties"]))# each range in data will only contain startRow and/or startColumn if they are not 0# (i.e. if you grab A1:___, you won't have startRow or startColumn)forrangeinsheet['data']:rowData=range.get('rowData',[])ifnotrowData:continueoffsets={'row':range.get('startRow',0),'col':range.get('startColumn',0)}rangeBGs=[default_bg]*offsets['row']rangeValues=['']*offsets['row']forrowinrowData:colData=row['values']newBGs=[default_bg]*offsets['col']newVals=['']*offsets['col']forcolincolData:try:newBGs.append(col['effectiveFormat']['backgroundColor'])exceptKeyError:newBGs.append(default_bg)# Shouldn't get called (all cells have a background)try:newVals.append(col['formattedValue'])# Always a string if present.exceptKeyError:newVals.append('')# Not all cells have a value.rangeBGs.append(newBGs)rangeValues.append(newVals)dataset.append({'sheetId':sheet['properties']['sheetId'],'sheetName':sheet['properties']['title'],'backgrounds':rangeBGs,'values':rangeValues})# dataset is now a list with elements that correspond to the requested ranges,# and contain 0-base row and column indexed arrays of the backgrounds and values.# One could add logic to pop elements from the ranges if the entire row has no values.# Color in A1 of 1st range:r1=dataset[0]print(f'Cell A1 color is {r1["backgrounds"][0][0]} and has value {r1["values"][0][0]}')print(f'Cell D2 color is {r1["backgrounds"][3][1]} and has value {r1["values"][3][1]}')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值