Answer a question

I have a Pandas dataframe that I am writing out to an XLSX using openpyxl. Many of the cells in the spreadsheet contain long sentences, and i want to set 'wrap_text' on all the contents of the sheet (i.e. every cell).

Is there a way to do this? I have seen openpyxl has an 'Alignment' option for 'wrap_text', but I cannot see how to apply this to all cells.

Edit:

Thanks to feedback, the following does the trick. Note - copy due to styles being immutable.

for row in ws.iter_rows():
    for cell in row:      
        cell.alignment =  cell.alignment.copy(wrapText=True)

Answers

Presumably, when you iterate through your cells, the idea would be to apply the format at that.

for row in ws.iter_rows():
    for cell in row:
        cell.style.alignment.wrap_text=True

There is also a fair amount more detail into how to use the wrap text style here Writing multi-line strings into cells using openpyxl

Hope this helps.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐