Dav*_*Gao 6 python excel charts export-to-excel
我一直在尝试在Excel中生成数据.我生成了.CSV文件.所以到目前为止这很容易.但是在Excel中生成图表非常困难......
我想知道,python是否能够在excel中生成数据和图形?如果有示例或代码片段,请随意发布:)
或者一个解决方法可以使用python以图形格式生成图形,如.jpg等.pdf文件也可以.只要解决方法不需要依赖,例如需要安装boost库.
Bry*_*nta 11
是的,Xlsxwriter [ docs ] [ pypi ] 在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
Run Code Online (Sandbox Code Playgroud)
您有 2 个选择:
如果您使用的是 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.
Run Code Online (Sandbox Code Playgroud)
如果您只想生成基本绘图等,您可以使用matplotlib。