使用openpyxl将'wrap_text'应用于所有单元格

Der*_*abe 7 python pandas openpyxl

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

有没有办法做到这一点?我看到openpyxl有'wrap_text'的'Alignment'选项,但我看不到如何将它应用于所有单元格.

编辑:

感谢反馈,以下是诀窍.注意 - 由于样式不可变而复制.

for row in ws.iter_rows():
    for cell in row:      
        cell.alignment =  cell.alignment.copy(wrapText=True)
Run Code Online (Sandbox Code Playgroud)

Sup*_*ova 13

我一直在使用openpyxl == 2.5.6.让我们说我们想要为单元格A1包装文本,然后我们可以使用下面的代码.

from openpyxl.styles import Alignment

ws['A1'].alignment = Alignment(wrap_text=True)
Run Code Online (Sandbox Code Playgroud)


use*_*089 11

import os
import openpyxl
from openpyxl.styles import Alignment, Font
from openpyxl.cell import Cell
#format cells with word wrap and top alignment    
for row in ws2.iter_rows():  
    for cell in row:      
        cell.alignment = Alignment(wrap_text=True,vertical='top') 
Run Code Online (Sandbox Code Playgroud)


小智 6

大概,当您遍历单元格时,想法是在那套格式。

for row in ws.iter_rows():
    for cell in row:
        cell.style.alignment.wrap_text=True
Run Code Online (Sandbox Code Playgroud)

这里还有很多有关如何使用自动换样式的详细信息, 使用openpyxl将多行字符串写入单元格

希望这可以帮助。

  • 当使用索引来调用单元格时,这应该起作用:`from openpyxl.styles import Alignment``_sheet.cell(1,2).alignment = Alignment(wrapText = True)` (3认同)

Dan*_*ein 5

更新 openpyxl v3 中的对齐方式

许多答案设置wrapText=True但破坏了现有的对齐选项。这可不行。

使用 openpyxl v3.0.4,我执行了以下操作:

import copy

for row in ws.iter_rows():
    for cell in row:      
        alignment = copy.copy(cell.alignment)
        alignment.wrapText=True
        cell.alignment = alignment
Run Code Online (Sandbox Code Playgroud)

原始海报的解决方案使用:

cell.alignment =  cell.alignment.copy(wrapText=True)
Run Code Online (Sandbox Code Playgroud)

但这产生了以下警告:

DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
  cell.alignment =  cell.alignment.copy(wrapText=True)
Run Code Online (Sandbox Code Playgroud)