问题
I'm trying to set wrap text. But when i using wrap text row doesn't change height automatically. How can I set auto-height row?
回答1:
You need to look at the RowDimension
object for the relevant row, specifically the height attribute:
rd = ws.row_dimensions[3] # get dimension for row 3
rd.height = 25 # value in points, there is no "auto"
回答2:
If your data stored in DataFrame, I would recommend you to use StyleFrame. It automatically auto-adjust columns width and rows height and also have some nice features.
styleframe
回答3:
Try:
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
Most updated version.
It's not perfect though. If you want better, you might have to use either monospace fonts or pillow
.
来源:https://stackoverflow.com/questions/37891149/openpyxl-auto-height-row