【发布时间】:2014-05-24 01:58:25
【问题描述】:
当使用 openpyxl 从 python 写入文件时,我希望 Excel 单元格中的文本与顶部对齐,而不是与底部对齐
【问题讨论】:
-
你的尝试在哪里?请在此处添加您的代码。
标签: python excel alignment cell openpyxl
当使用 openpyxl 从 python 写入文件时,我希望 Excel 单元格中的文本与顶部对齐,而不是与底部对齐
【问题讨论】:
标签: python excel alignment cell openpyxl
试试这个:
sheet["A1"].alignment.vertical = "top"
【讨论】:
这对我有用。我正在使用 openpyxl v2.5.8。
new_cell.alignment=Alignment(horizontal='general',
vertical='top',
text_rotation=0,
wrap_text=False,
shrink_to_fit=False,
indent=0)
欲了解更多信息:https://openpyxl.readthedocs.io/en/stable/styles.html?highlight=cell%20alignment
【讨论】:
您将单元格style.alignment.vertical 设置为所需的值。例如,要使单元格A1 垂直向上对齐:
# ws is worksheet
myCell = ws.cell('A1')
myCell.style.alignment.vertical = Alignment.VERTICAL_TOP
在课程参考页面here 上查找更多详细信息。
【讨论】:
使用两个循环将对齐格式应用于每个单元格。
al = Alignment(horizontal="left", vertical="top")
for row in sheet['A1':'A2']:
for cell in row:
cell.alignment = al
这个想法来自https://groups.google.com/forum/#!topic/openpyxl-users/GDrfknwrYEM
【讨论】: