我有一个excel文件:
Excel内容
我使用openpyxl绘制图表,但显示的日期格式不正确:
图表
我的代码:
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import (
ScatterChart,
Reference,
Series,
)
wb = load_workbook(filename = 'cat-test.xlsx')
ws = wb.get_sheet_by_name('ACZ')
chart = ScatterChart()
chart.title = "Scatter Chart"
chart.style = 13
chart.x_axis.title = 'Date'
chart.y_axis.title = 'Count'
chart.x_axis.number_format ='yyyy/mm/dd'
xvalues = Reference(ws, min_col=2, min_row=2, max_row=9)
for i in range(1, 2):
values = Reference(ws, min_col=i, min_row=1, max_row=9)
series = Series(values, xvalues, title_from_data=True)
chart.series.append(series)
ws.add_chart(chart, "A16")
wb.save("cat-test.xlsx")
请帮我解决一下,为什么这些年是1900年,谢谢!
答案 0 :(得分:1)
我想我解决了。我的参考是: http://openpyxl.readthedocs.io/en/default/charts/line.html#id1
我的新代码:
from openpyxl.chart.axis import DateAxis
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import (
LineChart,
Reference,
Series,
)
wb = load_workbook(filename = 'cat-test.xlsx')
ws = wb.get_sheet_by_name('ACZ')
chart = LineChart()
chart.title = "Line Chart"
chart.style = 13
chart.x_axis.title = 'Date'
chart.y_axis.title = 'Count'
chart.y_axis.crossAx = 500
chart.x_axis = DateAxis(crossAx=100)
chart.x_axis.number_format ='yyyy/mm/dd'
chart.x_axis.majorTimeUnit = "days"
data = Reference(ws, min_col=1, min_row=1, max_row=9)
chart.add_data(data, titles_from_data=True)
dates = Reference(ws, min_col=2, min_row=2, max_row=9)
chart.set_categories(dates)
ws.add_chart(chart, "A16")
wb.save("cat-test.xlsx")