以下代码将CSV作为输入,并输出包含条形图的XLSX:
import pandas
import sys
import openpyxl
from openpyxl.chart import BarChart, Reference
# ---- Data preparation ----
path = sys.argv[1]
df = pandas.read_csv(path, sep = "\t")
df = df[pandas.notnull(df['response_time'])]
df.loc[:, "datetime"].replace(to_replace = r"(.*T)", value = r"", inplace = True, regex = True)
df = pandas.pivot(df.datetime, df.name + '-' + df.type, df.response_time)
# ---- Prepare writer, workbook and worksheet ----
writer = pandas.ExcelWriter("test.xlsx", engine = 'xlsxwriter')
df.to_excel(writer, sheet_name = "graph")
workbook = writer.book
worksheet = writer.sheets["graph"]
# ---- USING OPENPYXL ----
chart1 = BarChart()
chart1.x_axis_title = "DateTime"
chart1.x_axis_title = "Response time"
data = Reference(workbook.active, min_col = 2, min_row = 1, max_col = len(df.columns) + 1, max_row = workbook.active.max_row)
xval = Reference(workbook.active, min_col = 1, min_row = 2, max_row = workbook.active.max_row)
chart1.add_data(data, titles_from_data = True)
chart1.set_categories(xval)
workbook.active.add_chart(chart1, "D4")
workbook.save("test.xlsx")
# ---- USING XLSXWRITER ----
chart = workbook.add_chart({'type' : 'column'})
for i in range(1, len(df.columns) + 1):
chart.add_series({
'name' : ['graph', 0, i],
'values' : ['graph', 1, i, len(df.index), i],
'categories': ['graph', 1, 0, len(df.index), 0],
})
chart.set_x_axis({'name' : 'DateTime'})
chart.set_y_axis({'name' : 'Response Time'})
worksheet.insert_chart('D4', chart)
writer.save()
输出图为:
openpyxl和xlsxwriter版本均产生完全相同的图。问题是xlsxwriter版本输出图是10MB,而openpyxl只有3MB。
经过调查,我发现xlsxwriter版本中的“类别”条目显着增加了权重。
当我发表评论时,我的X轴现在是从1到n的序列,但是输出只有1.6MB,那怎么可能?如何使用xlsxwriter使输出更轻量?
最佳答案
XlsxWriter文件可能更大,这是因为它存储了图表以及工作表的图表类别和数据值,就像Excel一样。这使Excel生成的文件具有更好的保真度,这是XlsxWriter的目标,并且在将图表嵌入到其他应用程序(如PowerPoint)中时,也可以减少问题。
根据您的分析,我猜想openpyxl不会存储其他数据。
如果您在Excel中重新保存XlsxWriter或openpyxl文件,我希望您最终得到的文件大小与XlsxWriter文件大致相同。
关于python - xlsxwriter图表类别文件大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53943798/