我正在尝试设置换行文字。但是当我使用换行文本行时不会自动更改高度。如何设置自动高度行?
答案 0 :(得分:7)
您需要查看相关行的RowDimension
对象,特别是height属性:
rd = ws.row_dimensions[3] # get dimension for row 3
rd.height = 25 # value in points, there is no "auto"
答案 1 :(得分:3)
如果您的数据存储在DataFrame中,我建议您使用StyleFrame。 它会自动自动调整列宽和行高,并且还有一些很好的功能。
答案 2 :(得分:0)
尝试:
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
。
答案 3 :(得分:0)
您可以使用row_dimensions或column_dimensions属性设置高度或宽度:
while