Python如何读取Excel多工作表并在各表内生成对应数据图表
实现方案
你可以通过将Plotly生成的图表导出为静态图片,再插入到对应Excel工作表的方式完成需求,全程无需打开浏览器,步骤及可运行代码如下:
依赖安装
先安装所需的第三方库:
pip install pandas openpyxl plotly kaleido
注:如果你的源文件是
.xls格式,需要额外安装xlrd==1.2.0读取xls文件,后续建议转成.xlsx格式处理兼容性更好。
完整实现代码
import plotly.graph_objects as go import pandas as pd from openpyxl import load_workbook from openpyxl.drawing.image import Image import os # 配置参数 excel_file = 'sample.xlsx' # 若为xls格式可直接修改为对应文件名 output_excel = 'output_with_charts.xlsx' # 生成新文件避免修改原数据 temp_img_path = 'temp_chart.png' # 临时图片存储路径,运行后自动删除 # 读取Excel所有工作表名称 xl = pd.ExcelFile(excel_file) sheet_names = xl.sheet_names # 先将所有工作表原始数据写入新Excel with pd.ExcelWriter(output_excel, engine='openpyxl') as writer: for sheet in sheet_names: df = pd.read_excel(excel_file, sheet_name=sheet) df.to_excel(writer, sheet_name=sheet, index=False) # 加载带数据的新Excel,逐个插入对应图表 wb = load_workbook(output_excel) for sheet_name in sheet_names: ws = wb[sheet_name] # 读取当前工作表数据 df = pd.read_excel(excel_file, sheet_name=sheet_name) # 生成Plotly散点图 fig = go.Figure(go.Scatter(x=df['Data'], y=df['Current'])) # 导出为临时png图片,可自定义尺寸 fig.write_image(temp_img_path, width=800, height=500) # 插入图片到当前工作表指定位置,示例为D2单元格,可自行调整 img = Image(temp_img_path) ws.add_image(img, 'D2') # 保存最终Excel文件 wb.save(output_excel) # 清理临时图片 if os.path.exists(temp_img_path): os.remove(temp_img_path)
代码说明
- 先批量读取所有工作表名称,遍历处理每一张表的数据
- 优先将原始数据写入新结果文件,避免误操作丢失原文件内容
- 每个工作表生成对应散点图后导出为临时图片,插入到工作表指定位置
- 运行完成后自动清理临时文件,最终生成的
output_with_charts.xlsx即为带图表的结果文件
可选优化方案
如果需要生成可在Excel内直接编辑的原生图表(非静态图片),可以换用xlsxwriter作为导出引擎,调用其内置的图表API生成原生Excel图表即可。
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

