简体   繁体   中英

Adding a text box to an excel chart using openpyxl

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?

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.

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 (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM