如何在openpyxl ch中显示日期格式

2024-03-28 18:02:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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年,谢谢!在


Tags: fromimportwstitlechart图表loadmin
1条回答
网友
1楼 · 发布于 2024-03-28 18:02:52

我想我解决了。我的参考号是: 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")

my excel line chart

相关问题 更多 >