使用Python生成Excel图表
我一直在尝试在Excel中生成数据。 我生成了一个.CSV文件。 到这里为止其实很简单。 但是在Excel中生成图表就比较难了……
我在想,Python能否同时在Excel中生成数据和图表? 如果有示例或者代码片段,欢迎分享哦 :)
或者可以用Python生成图表,保存成图像格式,比如.jpg,或者.pdf文件也可以……只要这个方法不需要安装像boost库这样的依赖就行。
5 个回答
2
我建议你试试gnuplot,它可以帮助你从数据文件中绘制图表。
17
是的,Xlsxwriter[文档][下载链接]在用Python创建Excel 图表方面非常有用。不过,你需要使用xlsx这种文件格式,而且如果参数设置不正确,反馈信息不多,另外你也不能读取你生成的输出。
import xlsxwriter
import random
# Example data
# Try to do as much processing outside of initializing the workbook
# Everything beetween Workbook() and close() gets trapped in an exception
random_data = [random.random() for _ in range(10)]
# Data location inside excel
data_start_loc = [0, 0] # xlsxwriter rquires list, no tuple
data_end_loc = [data_start_loc[0] + len(random_data), 0]
workbook = xlsxwriter.Workbook('file.xlsx')
# Charts are independent of worksheets
chart = workbook.add_chart({'type': 'line'})
chart.set_y_axis({'name': 'Random jiggly bit values'})
chart.set_x_axis({'name': 'Sequential order'})
chart.set_title({'name': 'Insecure randomly jiggly bits'})
worksheet = workbook.add_worksheet()
# A chart requires data to reference data inside excel
worksheet.write_column(*data_start_loc, data=random_data)
# The chart needs to explicitly reference data
chart.add_series({
'values': [worksheet.name] + data_start_loc + data_end_loc,
'name': "Random data",
})
worksheet.insert_chart('B1', chart)
workbook.close() # Write to file
3
你有两个选择:
如果你使用的是Windows系统,可以使用pywin32这个库(它包含在ActivePython里),通过OLE自动化来操作Excel。
from win32com.client import Dispatch
ex = Dispatch("Excel.Application")
# you can use the ex object to invoke Excel methods etc.
如果你只是想生成一些基本的图表等,可以使用matplotlib。