我正在尝试设置换行文本。但是当我使用换行文本行时不会自动更改高度。如何设置自动行高?
您需要查看相关行的
RowDimension
对象,特别是高度属性:
rd = ws.row_dimensions[3] # get dimension for row 3
rd.height = 25 # value in points, there is no "auto"
您可以使用row_dimensions或column_dimensions属性来设置高度或宽度:
# set the height of the row
sheet.row_dimensions[1].height = 20
# set the width of the column
sheet.column_dimensions['B'].width = 20
像这样尝试,它对我有用:
from math import ceil
factor_of_font_size_to_width = {
# TODO: other sizes
12: {
"factor": 0.8, # width / count of symbols at row
"height": 16
}
}
def get_height_for_row(sheet, row_number, font_size=12):
font_params = factor_of_font_size_to_width[font_size]
row = list(sheet.rows)[row_number]
height = font_params["height"]
for cell in row:
words_count_at_one_row = sheet.column_dimensions[cell.column_letter].width / font_params["factor"]
lines = ceil(len(str(cell.value)) / words_count_at_one_row)
height = max(height, lines * font_params["height"])
return height
for i in range(0, sheet.max_row):
# [i + 1] - because the lines are numbered starting at 1
sheet.row_dimensions[i + 1].height = get_height_for_row(sheet, i)
如果您的数据存储在DataFrame中,我建议您使用StyleFrame。 它会自动调整列宽和行高,并且还有一些不错的功能。
尝试:
col_width = []
for i in range(len(next(ws.iter_rows()))):
col_letter = get_column_letter(i + 1)
minimum_width = 20
current_width = ws.column_dimensions[col_letter].width
if not current_width or current_width < minimum_width:
ws.column_dimensions[col_letter].width = minimum_width
col_width.append(ws.column_dimensions[col_letter].width)
for i, row in enumerate(ws):
default_height = 12.5 # Corresponding to font size 12
multiples_of_font_size = [default_height]
for j, cell in enumerate(row):
wrap_text = True
vertical = "top"
if cell.value is not None:
mul = 0
for v in str(cell.value).split('\n'):
mul += math.ceil(len(v) / col_width[j]) * cell.font.size
if mul > 0:
multiples_of_font_size.append(mul)
cell.alignment = Alignment(wrap_text=wrap_text, vertical=vertical)
original_height = ws.row_dimensions[i + 1].height
if original_height is None:
original_height = default_height
new_height = max(multiples_of_font_size)
if original_height < new_height:
ws.row_dimensions[i + 1].height = new_height
但它并不完美。如果您想要更好,您可能必须使用等宽字体或
pillow
。
您可以将行高设置为“无”。如果这样做,则在 .xlsx 文件的 x1/worksheets/sheet.xml 文件中,行元素将没有为行高设置显式值。 Excel 将根据内容自动调整行高。
#Autofit the row height
sheet.row_dimensions[1].height = None