我正在尝试在openpyxl中对齐一列但没有成功:
wb = Workbook()
ws = wb.active
...
ws.column_dimensions["A"].alignment = Alignment(horizontal='left')
ws.column_dimensions["C"].alignment = Alignment(horizontal='center')
同样的:
ws["A"].alignment = Alignment(horizontal='left')
ws["C"].alignment = Alignment(horizontal='center')
这对我不起作用。
否则,迭代虽然单元格和对齐工作正常!!
答案 0 :(得分:4)
你应该得到失败的回溯!
如果您发布问题,请告诉我们!
ws["A"].alignment = Alignment(horizontal='left')
AttributeError: 'tuple' object has no attribute 'alignment'
未实现样式范围甚至整列。 你必须自己做。例如:
for row in rows:
cell_A = row[:1][0]
cell_A.alignment = Alignment(horizontal='left')
使用Python测试:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2
答案 1 :(得分:1)
from openpyxl import load_workbook
from openpyxl.styles import Alignment
xlsx_file = 'file.xlsx'
# openning:
wb = load_workbook(filename = xlsx_file)
# center align column H in the default sheet:
ws = wb.active
for row in ws[2:ws.max_row]: # skip the header
cell = row[7] # column H
cell.alignment = Alignment(horizontal='center')
# saving:
wb.save(xlsx_file)
答案 2 :(得分:-3)