openpyxl中的水平文本对齐方式

Pyt*_*zer 13 python xlsx openpyxl

我尝试将文本对齐方式更改为2个合并销售的中心,我发现了一些对我的案例不起作用的答案

currentCell = ws.cell('A1')
currentCell.style.alignment.horizontal = 'center' #TypeError: cannot set horizontal attribute
#or
currentCell.style.alignment.vertical = Alignment.HORIZONTAL_CENTER #AttributeError: type object 'Alignment' has no attribute 'HORIZONTAL_CENTER'
Run Code Online (Sandbox Code Playgroud)

两者都没有用,还有其他办法吗?

sam*_*ia7 29

是的,有一种方法可以使用openpyxl:

from openpyxl.styles import Alignment

currentCell = ws.cell('A1') #or currentCell = ws['A1']
currentCell.alignment = Alignment(horizontal='center')
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助


nmz*_*787 6

这是我最终使用PIP的最新版本(2.2.5)

    # center all cells
    for col in w_sheet.columns:
        for cell in col:
            # openpyxl styles aren't mutable,
            # so you have to create a copy of the style, modify the copy, then set it back
            alignment_obj = cell.alignment.copy(horizontal='center', vertical='center')
            cell.alignment = alignment_obj
Run Code Online (Sandbox Code Playgroud)


小智 5

其他解决方案都不适合我,因为我的解决方案需要 openpyxl,并且至少在 2.1.5 cell.alignment 中不能直接设置。

from openpyxl.styles import Style, Alignment

cell = ws.cell('A1')
cell.style = cell.style.copy(alignment=Alignment(horizontal='center')) 
Run Code Online (Sandbox Code Playgroud)

以上复制当前样式并替换对齐方式。您还可以创建全新的样式 - 任何未指定的值均采用https://openpyxl.readthedocs.org/en/latest/styles.html 中的默认值

cell.style = Style(alignment=Alignment(horizontal='center'),font=Font(bold=True))

# or - a tidier way

vals = {'alignment':Alignment(horizontal='center'),
        'font':Font(bold=True),
       }
new_style = Style(**vals)
cell.style = new_style
Run Code Online (Sandbox Code Playgroud)

  • 不再使用`Style` 类;您可以直接分配给各个样式元素。对于此示例,您将分配 `cell.font = Font(bold=True)` 和 `cell.alignment = Alignment(horizo​​ntal='center')` 和(不在示例中)`cell.fill = PatternFill(fgColor= '33489F',fill_type='solid')` (2认同)