如何提取Excel工作表样式并完整应用到Pandas DataFrame
Excel样式复刻到Pandas DataFrame的实现方案
可通过两种成熟路径实现需求,无需手动转换Excel到HTML做模板适配:
方案1:使用StyleFrame库实现(推荐,适配90%以上场景)
StyleFrame是专门对接Pandas和Excel样式的第三方库,可直接读取Excel样式并映射到DataFrame结构:
- 安装依赖:
pip install styleframe openpyxl pandas - 代码示例:
from StyleFrame import StyleFrame, utils # 读取带完整样式的源Excel source_sf = StyleFrame.read_excel("源样式文件.xlsx", read_style=True, use_openpyxl_styles=True) # 你的目标DataFrame,需和源Excel行列结构对齐 target_df = pd.read_csv("你的数据文件.csv") target_sf = StyleFrame(target_df) # 1:1复刻源Excel的行高、列宽、单元格样式 for row_idx in range(len(source_sf.data_df)): if row_idx >= len(target_sf.data_df): break # 同步行高 target_sf.set_row_height(row_idx + 1, source_sf.get_row_height(row_idx + 1)) for col_idx in range(len(source_sf.data_df.columns)): if col_idx >= len(target_sf.data_df.columns): break # 同步列宽 col_letter = utils.get_column_letter(col_idx + 1) target_sf.set_column_width(col_letter, source_sf.get_column_width(col_letter)) # 同步单元格样式 target_sf.style_df.iloc[row_idx, col_idx] = source_sf.style_df.iloc[row_idx, col_idx] # 导出为带样式的Excel,或生成HTML渲染 target_sf.to_excel("输出带样式文件.xlsx").save() html_content = target_sf.to_html()
方案2:基于Pandas原生Styler实现(适合自定义程度高的场景)
你之前尝试的自定义模板路径兼容性较差,可直接通过openpyxl读取Excel样式属性,再映射到Styler配置:
import pandas as pd from openpyxl import load_workbook from pandas.io.formats.style import Styler # 读取源Excel wb = load_workbook("源样式文件.xlsx", data_only=True) ws = wb.active # 生成目标DataFrame df = pd.DataFrame(ws.values) df.columns = df.iloc[0] df = df[1:].reset_index(drop=True) # 样式映射函数 def map_excel_style(styler, worksheet): max_row = min(worksheet.max_row, len(df) + 1) max_col = min(worksheet.max_column, len(df.columns)) styles = [] for row in range(2, max_row + 1): # 跳过表头行 for col in range(1, max_col + 1): cell = worksheet.cell(row=row, column=col) # 提取样式属性 bg = cell.fill.fgColor.rgb[2:] if cell.fill.patternType else "transparent" font_color = cell.font.color.rgb[2:] if cell.font.color else "000000" bold = "bold" if cell.font.bold else "normal" align = cell.alignment.horizontal or "left" # 添加样式规则 styles.append({ "selector": f"tbody tr:nth-child({row-1}) td:nth-child({col})", "props": [ ("background-color", f"#{bg}" if bg != "transparent" else bg), ("color", f"#{font_color}"), ("font-weight", bold), ("text-align", align) ] }) styler.set_table_styles(styles) return styler # 应用样式并渲染 styler = Styler(df) styled_styler = map_excel_style(styler, ws) html_output = styled_styler.to_html()
- 两种方案都需要源Excel的行列结构和目标DataFrame对齐,才能实现完整样式复刻
- 若源Excel包含合并单元格、条件格式、边框等复杂样式,优先使用方案1实现,无需额外写适配逻辑
内容的提问来源于stack exchange,提问作者Akmal Soliev
相关产品推荐
相关产品推荐

