问题
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