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)
希望对你有帮助
这是我最终使用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)
| 归档时间: |
|
| 查看次数: |
27325 次 |
| 最近记录: |