如何通过 Google Sheets API 获取文本旋转角度?
结论
Google Sheets API 的 TextRotation 对象有两种互斥的旋转类型:angle 和 vertical。要读取倾斜角度,请检查响应中单元格的 userEnteredFormat.textRotation.angle 或 effectiveFormat.textRotation.angle。提问中的字段掩码已包含 textRotation,可以将其写为 textRotation(angle,vertical),并确认代码从目标单元格的目标格式字段中读取 angle。
API 文档规定,angle 是取值范围为 -90 到 90 的整数;vertical 表示逐字纵向排列。由于两者属于同一个联合字段,如果对象中只有 "vertical": false,就无法从中读取角度。Google Sheets API:TextRotation
请求角度字段
在字段掩码中明确列出 angle 和 vertical。你的请求包含两种格式对象,可以按下面的方式调整相应部分:
fields = """sheets(properties(sheetId,title),merges,bandedRanges,data(rowData(values(userEnteredValue,effectiveValue,formattedValue,userEnteredFormat(backgroundColor,horizontalAlignment,verticalAlignment,textRotation(angle,vertical),textFormat,borders),effectiveFormat(backgroundColor,textRotation(angle,vertical),textFormat,borders)))))"""
sheet = service.spreadsheets().get(
spreadsheetId=sheet_id,
includeGridData=True,
fields=fields,
).execute()
然后从单元格的 userEnteredFormat 或 effectiveFormat 中读取角度。响应可能省略未设置的字段,因此读取时可以使用 .get():
for sheet_data in sheet.get("sheets", []):
for grid_data in sheet_data.get("data", []):
for row in grid_data.get("rowData", []):
for cell in row.get("values", []):
user_rotation = (
cell.get("userEnteredFormat", {}).get("textRotation", {})
)
effective_rotation = (
cell.get("effectiveFormat", {}).get("textRotation", {})
)
print(
"user-entered angle:", user_rotation.get("angle"),
"effective angle:", effective_rotation.get("angle"),
"vertical:", user_rotation.get("vertical"),
)
如何判断读取结果
- 单元格使用倾斜文本时,检查对应
textRotation对象中的angle。 - 单元格使用逐字纵向排列时,检查
vertical是否为true。此时角度字段不适用。 - 如果没有
angle,先核对返回的单元格位置,再检查userEnteredFormat和effectiveFormat两条路径。缺少angle本身无法提供可读取的整数值。
提问中的响应片段只有 "vertical": false,没有 angle。仅凭这段内容,无法判断目标单元格是否设置了倾斜角度。如果明确设置过角度,但两个格式对象中都没有 angle,建议单独检查目标单元格的完整 API 响应,并确认读取的网格范围和格式路径与实际设置一致。
注意事项
userEnteredFormat 表示用户输入的格式,effectiveFormat 表示单元格的有效格式。转换为 Markdown 时,可以根据需求选择其中一种作为格式来源。如果没有角度字段,应保留为未提供,不要把 vertical: false 当作角度值。
备注:内容仅供参考。
