openpyxl中的水平文本对齐方式

时间:2014-10-31 09:44:51

标签: 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'

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

4 个答案:

答案 0 :(得分:22)

是的,有一种方法可以使用openpyxl执行此操作:

from openpyxl.styles import Alignment

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

希望这会对你有所帮助

答案 1 :(得分:6)

这是我最终使用PIP(2.2.5)

的最新版本
{{1}}

答案 2 :(得分:3)

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

答案 3 :(得分:1)

您可以使用Python XlsxWriter库来实现此目的。

import xlsxwriter

workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()

cell_format = workbook.add_format({'align': 'center'})

worksheet.merge_range('A1:B1', "")
worksheet.write_rich_string('A1','Example', cell_format)

workbook.close()

这里我合并了单元格A1,B1并添加了一个单元格格式参数,其中包含指定为中心的对齐参数。

enter image description here