【发布时间】:2019-07-31 05:26:23
【问题描述】:
我希望通过导出 pandas 数据框并使用 openpyxl 绘制数据来将新工作表添加到 excel 文件中。目前我可以添加一个新工作表并插入熊猫数据框,但不能插入数据图。
目前我的代码如下所示。
import pandas
import openpyxl
from openpyxl.chart import LineChart, Reference
fileSavePath = 'C:/Users/PATH'
filename = "Existing Excel File"
lst1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst2 = [0, 5, 2, 8, 15, 7, 10, 4, 0]
df = pandas.DataFrame({'First Column': lst1, 'Second Column': lst2})
book = openpyxl.load_workbook(fileSavePath + filename + '.xlsx')
with pandas.ExcelWriter(fileSavePath + filename + '.xlsx', engine='openpyxl') as writer:
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, 'new_sheet', index=False)
wb = openpyxl.Workbook()
sheet = wb.active
values = Reference(sheet, min_col=1, min_row=1,
max_col=1, max_row=len(lst1))
chart = LineChart()
chart.add_data(values)
chart.title = " LINE-CHART "
chart.x_axis.title = " X-AXIS "
chart.y_axis.title = " Y-AXIS "
sheet.add_chart(chart, "E2")
writer.save()
writer.close()
目前没有错误,数据框写入但图表没有出现在新添加的工作表中。
【问题讨论】: