pandas 使用 openpyxl 将“wrap_text”应用于所有单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42215933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:58:48  来源:igfitidea点击:

Apply 'wrap_text' to all cells using openpyxl

pythonpandasopenpyxl

提问by DerRabe

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).

我有一个 Pandas 数据框,我正在使用 openpyxl 将其写入 XLSX。电子表格中的许多单元格都包含长句,我想在工作表的所有内容(即每个单元格)上设置“wrap_text”。

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.

有没有办法做到这一点?我已经看到 openpyxl 有一个“wrap_text”的“对齐”选项,但我看不到如何将它应用于所有单元格。

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)

回答by SuperNova

I have been using openpyxl>=2.5.6. Let us say we want to wrap text for cell A1, then we can use the below code.

我一直在用openpyxl>=2.5.6。假设我们要为单元格 A1 换行,那么我们可以使用以下代码。

from openpyxl.styles import Alignment

ws['A1'].alignment = Alignment(wrap_text=True)

回答by Allan B

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

关于如何在此处使用换行文本样式的更多详细信息 使用 openpyxl 将多行字符串写入单元格

Hope this helps.

希望这可以帮助。

回答by stovfl

Iterates all cells

迭代所有单元格

  for rows in ws.iter_rows(min_row=1, min_col=1):
    for cell in rows:
      print('cell %s %s' % (cell.coordinate,cell.value))

* Tested with Python:3.4.2 - openpyxl:2.4.1 *

* 使用 Python:3.4.2 测试 - openpyxl:2.4.1 *