openpyx中的水平文本对齐

2024-03-29 06:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将文本对齐改为两个合并销售的中心,我找到了一些对我的案例无效的答案

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'

两个都没用,还有别的办法吗?


Tags: 答案文本wsstylecellattribute中心案例
3条回答

这就是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

其他的解决方案都不适合我,因为我的解决方案需要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')) 

以上内容将复制当前样式并替换对齐方式。 您还可以创建一个全新的样式-任何未指定的值都取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

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

from openpyxl.styles import Alignment

currentCell = ws.cell('A1') #or currentCell = ws['A1']
currentCell.alignment = Alignment(horizontal='center')

希望这对你有帮助

相关问题 更多 >