使用Pandas提取XLSX模板工作表格式与数据的技术问题咨询
解决XLSX模板数据与格式提取问题
嘿,我太懂你现在的困扰了——只提取到数据却拿不到模板里的字体、颜色、对齐方式这些格式细节,确实会让模板复用或者格式还原变得无从下手。我之前做报表模板工具的时候也踩过这个坑,下面就给你分享用Python的openpyxl库(专门针对XLSX格式的神器)来同时提取数据和格式的实用方法:
核心思路:启用格式读取支持
openpyxl默认就支持读取单元格格式,关键是加载工作簿时要注意参数设置:
data_only=False:保留单元格的原始公式(如果有的话),同时不影响格式读取;如果只需要计算后的数值,设为True也没问题,格式信息依然能获取。
提取常见格式属性
下面是最常用的格式类型及对应的代码示例:
1. 字体格式(字体名称、大小、加粗、斜体等)
font = cell.font print(f"字体名称: {font.name}") print(f"字体大小: {font.size}") print(f"是否加粗: {font.bold}") print(f"是否斜体: {font.italic}") print(f"字体颜色: {font.color.rgb if font.color else '默认'}")
2. 单元格填充(背景色、填充样式)
fill = cell.fill if fill.patternType: # 只有设置了填充样式才会有值 print(f"填充样式: {fill.patternType}") print(f"前景色(背景色): {fill.fgColor.rgb}") print(f"背景色: {fill.bgColor.rgb}")
3. 对齐方式(水平/垂直对齐、自动换行等)
alignment = cell.alignment print(f"水平对齐: {alignment.horizontal}") print(f"垂直对齐: {alignment.vertical}") print(f"是否自动换行: {alignment.wrapText}") print(f"文本缩进: {alignment.indent}")
4. 边框样式(各边的边框类型、颜色)
border = cell.border print(f"上边框样式: {border.top.style} | 颜色: {border.top.color.rgb if border.top.color else '默认'}") print(f"下边框样式: {border.bottom.style} | 颜色: {border.bottom.color.rgb if border.bottom.color else '默认'}") print(f"左边框样式: {border.left.style} | 颜色: {border.left.color.rgb if border.left.color else '默认'}") print(f"右边框样式: {border.right.style} | 颜色: {border.right.color.rgb if border.right.color else '默认'}")
5. 行高与列宽
这也是模板格式的重要部分,直接通过工作表对象获取:
# 获取第2行的行高 row_height = sheet.row_dimensions[2].height # 获取B列的列宽 col_width = sheet.column_dimensions['B'].width
完整示例代码
把这些整合起来,一次性提取数据和格式:
from openpyxl import load_workbook # 加载目标模板文件 wb = load_workbook("your_template.xlsx", data_only=False) target_sheet = wb["Sheet1"] # 替换成你要提取的工作表名称 # 遍历指定范围的单元格(这里是前5行前3列,可按需调整) for row in target_sheet.iter_rows(min_row=1, max_row=5, min_col=1, max_col=3): for cell in row: print(f"=== 单元格 {cell.coordinate} ===") print(f"数据值/公式: {cell.value}") # 提取字体信息 font = cell.font print(f"字体: {font.name} (大小: {font.size}, 加粗: {font.bold}, 颜色: {font.color.rgb if font.color else '默认'})") # 提取填充信息 fill = cell.fill if fill.patternType: print(f"填充: {fill.patternType} (前景色: {fill.fgColor.rgb})") # 提取对齐信息 alignment = cell.alignment print(f"对齐: 水平-{alignment.horizontal}, 垂直-{alignment.vertical}, 自动换行-{alignment.wrapText}") print("\n")
额外说明
- 如果你的模板里有条件格式,可以通过
target_sheet.conditional_formatting来获取,不过这部分逻辑相对复杂,需要根据规则类型逐一解析; - 若你使用的是其他编程语言(比如Java),可以用Apache POI库,思路类似:通过单元格对象获取CellStyle、Font等属性。
内容的提问来源于stack exchange,提问作者user9371527
相关产品推荐
相关产品推荐

