python OpenPyxl自动高度行

cczfrluj  于 2023-10-14  发布在  Python
关注(0)|答案(6)|浏览(273)

我正在尝试设置自动换行。但是当我使用文字换行时,行的高度不会自动改变。如何设置自动高度行?

js81xvg6

js81xvg61#

您需要查看相关行的RowDimension对象,特别是height属性:

rd = ws.row_dimensions[3] # get dimension for row 3
rd.height = 25 # value in points, there is no "auto"
fgw7neuy

fgw7neuy2#

可以使用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
brccelvz

brccelvz3#

试试这样,它对我的工作:

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)
ioekq8ef

ioekq8ef4#

如果你的数据存储在DataFrame中,我建议你使用StyleFrame。它可以自动调整列宽和行高,也有一些不错的功能。
styleframe

g2ieeal7

g2ieeal75#

试试看:

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

7gyucuyw

7gyucuyw6#

您可以将行高设置为“无”。如果这样做,那么在.xlsx文件的x1/worksheets/sheet.xml文件中,row元素将没有为行高设置显式值。Excel将根据内容自动调整行高。

#Autofit the row height
sheet.row_dimensions[1].height = None

相关问题