openpyxl中的文本水平对齐
我想把两个合并单元格的文字对齐到中间。我找了一些答案,但都不适合我的情况:
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'
这两个方法都不管用,还有其他办法吗?
6 个回答
1
这是我第一次在这里发帖。
我找到了一种使用 openpyxl 来对齐文本的方法,就是用 Alignment。
i=3
while i < 253:
cellc = ws.cell(row=i, column= 3)
cellc.alignment = Alignment(horizontal="right")
i+=1
我把 i 设置为起始点,然后是我列的长度。
2
我发现下面的代码是一个非常简单的方法,可以格式化你工作表中的每一个单元格:
tot_rows = ws.max_row #get max row number
tot_cols = ws.max_column #get max column number
cols = range(1,tot_cols) #turns previous variables into iterables
rows = range(1,tot_rows)
for c in cols:
for r in rows:
ws.cell(row=r, column=c).alignment = Alignment(horizontal='center', vertical='center')
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'))
上面的代码是复制当前的样式,然后替换对齐方式。你也可以创建一个全新的样式——如果没有指定的值,就会使用默认值,具体可以参考这个链接。
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
12
这是我用最新版本的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.4.0(大约在2016年)开始,.copy()
这个方法对于StyleProxy对象来说已经不再推荐使用了,具体可以查看这里。
试着把最后两行改成:
from copy import copy
alignment_obj = copy(cell.alignment)
alignment_obj.horizontal = 'center'
alignment_obj.vertical = 'center'
cell.alignment = alignment_obj
74
是的,使用openpyxl可以做到这一点:
from openpyxl.styles import Alignment
currentCell = ws.cell('A1') #or currentCell = ws['A1']
currentCell.alignment = Alignment(horizontal='center')
希望这能帮到你