python 如何使用OpenPyXL正确对齐Excel单元格中的文本,使其不会重复或溢出

ssm49v7z  于 2023-01-11  发布在  Python
关注(0)|答案(1)|浏览(207)

我正在使用openpyxl从头开始创建一个Excel。一些单元格填充了长字符串,如果字符串太长,我希望它在单元格边界处剪切,而不是溢出到相邻单元格。
这可以使用Alignment(horizontal='fill')来实现,但是如果字符串太短,它会重复该字符串以 * 填充 * 单元格。
怎样才能做到既不溢出又不重复?
没有Alignment(horizontal='fill')的溢出:

import openpyxl
from openpyxl.styles import NamedStyle

wb = openpyxl.Workbook()
cell_style = NamedStyle(name='cell_style')
wb.add_named_style(cell_style)

ws = wb.active
ws['A1'].value = 'abcdefghijklmnop'
ws['A1'].style = 'cell_style'

wb.save('example.xlsx')

输出:

Alignment(horizontal='fill')重复:

import openpyxl
from openpyxl.styles import NamedStyle, Alignment

cell_style = NamedStyle(name='cell_style')
cell_style.alignment = Alignment(horizontal='fill')

wb = openpyxl.Workbook()
wb.add_named_style(cell_style)
ws = wb.active
ws['A1'].value = 'abc'
ws['A1'].style = 'cell_style'
wb.save('example.xlsx')

输出:

f87krz0w

f87krz0w1#

您可以使用wrap_text并将行高恢复为默认值。对齐方式设置为垂直顶部,以便文本的开头显示在单元格中。

import openpyxl
from openpyxl.styles import NamedStyle, Alignment

cell_style = NamedStyle(name='cell_style')
cell_style.alignment = Alignment(vertical='top', wrap_text=True)

wb = openpyxl.Workbook()
wb.add_named_style(cell_style)
ws = wb.active
ws['A1'].value = 'abcdefghijklmnopq'
ws['A1'].style = 'cell_style'
ws['A2'].value = 'abc'
ws['A2'].style = 'cell_style'
for i in range(1,3):
    ws.row_dimensions[ws[f'A{i}'].row].height = ws.sheet_format.defaultRowHeight
wb.save('example.xlsx')

相关问题