Adding a text box to an excel chart using openpyxl

2019-07-23 17:29发布

问题:

I'm trying to add a text box to a chart I've generated with openpyxl, but can't find documentation or examples showing how to do so. Does openpyxl support it?

回答1:

I'm not sure what you mean by "text box". In theory you can add pretty much anything covered by the DrawingML specification to a chart but the practice may be slightly different.

However, there is definitely no built-in API for this so you'd have to start by creating a sample file and working backwards from it.



回答2:

I also haven't been able to figure out how to do this via OpenPyXL, but you can add a textbox using XLSXWriter.

Note that you can use both OpenPyXL and XLSXWriter at the same time, but it is important to complete the changes you are making in OpenPyXL and save/close the workbook before re-opening it in XLSXWriter and adding the textbox. (Otherwise, stating the obvious, you could save over any changes (e.g. the textbox) made by the second package.)

FWIW, on my laptop at least, the test workbook opens waaaaaay faster in XLSXWriter than it does in OpenPyXL. A workbook with 10 single-page worksheets, crammed with formulas, formatting, data - takes 8 secs to load in OpenPyXL and about .003 secs to load in XLSXWriter. So re-opening the workbook a second time is not that big a deal, even if processing dozens of workbooks.

Here is a simple code example for creating a textbox using XLSXWriter:

import xlsxwriter as xlwr
xlwrwb = xlwr.Workbook('c:\myworkbook.xlsx')
xlwrsheet = xlwrwb.get_worksheet_by_name(sheet.title)

rrow = 10
ccol = 8
ttxt = "This is an example textbox created by OpenPyXL." 
xlwropts = {
    'width': 400,
    'height':200,
    'fill': {'color': '#EEE8AA'},
    'align': {'vertical': 'middle', 'horizontal': 'center'},
    'font': {'bold': True, 'name': 'Arial', 'size': 16, 'color':'orange'},
}
xlwrsheet.insert_textbox(rrow,ccol,ttxt, xlwropts)
xlwrwb.close()

UPDATE:

Have been working on this example since posting above code and I stand corrected. The XLSXWriter docs certainly demonstrate adding a textbox as per above code, but XLSXWriter cannot make changes to an existing Excel workbook. It only can create new workbooks - and it cannot use an existing Excel workbook as a template, even.

I will attempt to find another package that can do this, but at this point it doesn't look good.

Here's hoping the good minds at OpenPyXL (Charlie?) can provide a near-enough solution using the DrawingML specification, but at this point that is beyond my own abilities.

https://xlsxwriter.readthedocs.io/faq.html