How To Position Chart in Workbook

不羁岁月 提交于 2019-12-07 12:24:20

问题


I am running python2.7, and using openpyxl version 1.8.6. I am able to generate a chart just fine, but am unable to locate anything that indicates the chart can then be positioned in a particular location in a sheet. Any assistance would be appreciated.

I am using the following code to generate the chart:

ws = wb2.get_sheet_by_name('Traffic Data')
rowcount = ws.get_highest_row()
values = Reference(ws,(1,1), (rowcount - 1,1))
labels = Reference(ws,(0,1),(rowcount,0))
title = "Events recorded in " + str(datetime.datetime.strptime(str(runmonth), '%m').strftime('%B'))
series = Series(values, title=title)
chart.add_series(series)
ws = wb2.get_sheet_by_name('Traffic Incidents')
ws.add_chart(chart)

回答1:


According to the source code it is not possible to set the exact location of the chart while adding it to the worksheet using add_chart().

Consider switching to the xlsxwriter module. Quote from Working with Charts:

# Create a new chart object.
chart = workbook.add_chart({'type': 'line'})

# Add a series to the chart.
chart.add_series({'values': '=Sheet1!$A$1:$A$6'})

# Insert the chart into the worksheet.
worksheet.insert_chart('C1', chart)



回答2:


I was able to offset the chart position by using chart.drawing. Specifically, I used:

chart.drawing.left = 1000

This offset the chart by about 11 cells. I'm not sure about the pixel to cell mapping, but it can be easily reverse engineered by a few trials.




回答3:


It's actually really difficult to set the position of any object in Excel because it uses an absurdly stupid system for cell widths: these are based on the width of a number of characters in a particular font and size plus some padding. Charts on the other hand have to be positioned using pixels. We do have the point_pos() method in worksheets but I wouldn't trust it. We've just release 2.0 which has cleaner code. Basically you can play around with the chart.drawing attributes to get it where you need at in what size.

Take look at the code in charts/chart.py for more information. The next release should be a bit more comfortable.



来源:https://stackoverflow.com/questions/23617280/how-to-position-chart-in-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!