如何将Pandas DataFrame导出为类Excel样式的PNG文件?
解决DataFrame导出类Excel样式表格的方案
方法1:Pandas Styler + HTML转图片
用Pandas自带的Styler可以完全复刻Excel的自定义样式(包括单元格颜色、边框、字体对齐等),再通过基础工具把生成的HTML转成图片:
- 定义类Excel样式并导出HTML
import pandas as pd import numpy as np # 生成测试数据 df = pd.DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C']) # 配置样式 styler = df.style \ .set_table_styles([ # 表头样式:蓝色背景、白色字体、黑色边框、居中对齐 {'selector': 'th', 'props': [('background-color', '#4F81BD'), ('color', 'white'), ('border', '1px solid #000'), ('text-align', 'center')]}, # 单元格样式:黑色边框、右对齐 {'selector': 'td', 'props': [('border', '1px solid #000'), ('text-align', 'right')]}, # 表格合并边框 {'selector': 'table', 'props': [('border-collapse', 'collapse'), ('width', '60%')]} ]) \ .highlight_max(color='#C6EFCE') # 高亮最大值 .highlight_min(color='#FFC7CE') # 高亮最小值 # 保存为HTML文件 styler.to_html('styled_table.html')
- HTML转PNG
使用imgkit(跨平台,依赖wkhtmltopdf,可通过包管理器或官网安装):
import imgkit imgkit.from_file('styled_table.html', 'styled_table.png', options={'quiet': ''})
方法2:openpyxl生成样式Excel + 跨平台工具转图片
用openpyxl(Python原生Excel处理模块)生成带样式的Excel,再用LibreOffice命令行转成图片:
- 给Excel添加样式
from openpyxl import Workbook from openpyxl.styles import PatternFill, Border, Side, Alignment, Font from openpyxl.utils.dataframe import dataframe_to_rows wb = Workbook() ws = wb.active # 写入DataFrame数据 for row in dataframe_to_rows(df, index=False, header=True): ws.append(row) # 定义样式参数 header_fill = PatternFill(start_color='#4F81BD', end_color='#4F81BD', fill_type='solid') thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')) header_font = Font(color='FFFFFF', bold=True) # 应用表头样式 for cell in ws[1]: cell.fill = header_fill cell.font = header_font cell.border = thin_border cell.alignment = Alignment(horizontal='center') # 应用单元格样式并高亮极值 for row in ws.iter_rows(min_row=2): for cell in row: cell.border = thin_border cell.alignment = Alignment(horizontal='right') col_name = cell.column_letter if cell.value == df[col_name].max(): cell.fill = PatternFill(start_color='#C6EFCE', end_color='#C6EFCE', fill_type='solid') elif cell.value == df[col_name].min(): cell.fill = PatternFill(start_color='#FFC7CE', end_color='#FFC7CE', fill_type='solid') wb.save('styled_excel.xlsx')
- Excel转PNG
安装LibreOffice后,执行命令行(跨平台支持):
libreoffice --headless --convert-to png --outdir ./ styled_excel.xlsx
方法3:Plotly生成表格并导出图片
Plotly的表格组件可以快速实现Excel风格,直接导出为PNG:
import plotly.graph_objects as go fig = go.Figure(data=[go.Table( header=dict(values=list(df.columns), fill_color='#4F81BD', font=dict(color='white', size=12), align='center'), cells=dict(values=[df.A, df.B, df.C], fill_color='white', align='right', line_color='black')) ]) fig.update_layout(width=600, height=400) # 需要先安装kaleido:pip install kaleido fig.write_image('plotly_table.png')
内容的提问来源于stack exchange,提问作者Bython
相关产品推荐
相关产品推荐

