Python -自动调整excel文件列的宽度

ttisahbt  于 2023-02-10  发布在  Python
关注(0)|答案(9)|浏览(343)

新手-我有一个Python脚本,可以根据指定的值调整excel文件中不同列的宽度:

import openpyxl
from string import ascii_uppercase

newFile = "D:\Excel Files\abc.xlsx"

wb = openpyxl.load_workbook(filename = newFile)        
worksheet = wb.active

for column in ascii_uppercase:
    if (column=='A'):
        worksheet.column_dimensions[column].width = 30
    elif (column=='B'):
        worksheet.column_dimensions[column].width = 40            
    elif (column=='G'):
        worksheet.column_dimensions[column].width = 45            
    else:
        worksheet.column_dimensions[column].width = 15

wb.save(newFile)

有没有什么方法可以把每一列的宽度调整到最佳值,而不需要为不同的列显式指定宽度(也就是说,不需要使用这个“if-elif-elif-...... -elif-else”结构)?谢谢!

qvsjd97n

qvsjd97n1#

for col in worksheet.columns:
     max_length = 0
     column = col[0].column_letter # Get the column name
     for cell in col:
         try: # Necessary to avoid error on empty cells
             if len(str(cell.value)) > max_length:
                 max_length = len(str(cell.value))
         except:
             pass
     adjusted_width = (max_length + 2) * 1.2
     worksheet.column_dimensions[column].width = adjusted_width

这可能会做得更简洁,但它确实起作用了。你会想根据你在查看它时使用的字体的好坏来调整adjusted_width的值。如果你使用monotype,你可以得到它的精确值,但它不是一对一的相关性,所以你仍然需要调整它一点。
如果你想在不使用monotype的情况下变得花哨和精确,你可以按宽度排序字母,并为每个宽度分配一个浮点值,然后相加。这将需要第三个循环来解析单元格值中的每个字符,并对每列的结果求和,可能还需要一个字典来按宽度排序字符,也许有点夸张,但如果你这样做的话很酷。
编辑:实际上似乎有一种更好的方法来测量文本的视觉大小:link我个人更喜欢matplotlib技术。
希望我能帮上忙,我的第一个stackoverflow回答=)

6ss1mwsb

6ss1mwsb2#

openpyxl 3.0.0的更新版本(在TypeError: expected <class 'str'>中使用.columns失败:

for column_cells in ws.columns:
    length = max(len(str(cell.value)) for cell in column_cells)
    ws.column_dimensions[column_cells[0].column_letter].width = length
b4lqfgs4

b4lqfgs43#

在最新的openpyxl中,你可以使用:

from openpyxl.utils import get_column_letter
for idx, col in enumerate(worksheet.columns, 1):
    worksheet.column_dimensions[get_column_letter(idx)].auto_size = True
5tmbdcev

5tmbdcev4#

根据上面的评论,并添加此帖子openpyxl - adjust column width size .我成功了,但答案应该是:

from openpyxl.utils import get_column_letter

for col in ws.columns:
    max_length = 0
    column = get_column_letter(col[0].column)  # Get the column name
    # Since Openpyxl 2.6, the column name is  ".column_letter" as .column became the column number (1-based)
    for cell in col:
        try:  # Necessary to avoid error on empty cells
            if len(str(cell.value)) > max_length:
                max_length = len(cell.value)
        except:
            pass
    adjusted_width = (max_length + 2) * 1.2
    ws.column_dimensions[column].width = adjusted_width

我正在使用openpyxl =“^3.0.5”

mnowg1ta

mnowg1ta5#

我遇到了merged_cells和autosize无法正常工作的问题,如果您遇到了同样的问题,您可以通过在oldsea代码中添加下一行来解决

for col in worksheet.columns:
    max_length = 0
    column = col[0].column # Get the column name
    for cell in col:
        if cell.coordinate in worksheet.merged_cells: # not check merge_cells
            continue
        try: # Necessary to avoid error on empty cells
            if len(str(cell.value)) > max_length:
                max_length = len(cell.value)
        except:
            pass
    adjusted_width = (max_length + 2) * 1.2
    worksheet.column_dimensions[column].width = adjusted_width
fnvucqvd

fnvucqvd6#

只需要在你的文件中插入下面的代码行。就这样(如果你没有,安装上面提到的库)

# Imorting the necessary modules
try:
        from openpyxl.cell import get_column_letter
except ImportError:
        from openpyxl.utils import get_column_letter
        from openpyxl.utils import column_index_from_string
from openpyxl import load_workbook
import openpyxl
from openpyxl import Workbook


for column_cells in sheet.columns:
    new_column_length = max(len(str(cell.value)) for cell in column_cells)
    new_column_letter = (get_column_letter(column_cells[0].column))
    if new_column_length > 0:
        sheet.column_dimensions[new_column_letter].width = new_column_length*1.23
vi4fp9gy

vi4fp9gy7#

for column_cells in sheet.columns:
    new_column_length = max(len(str(cell.value)) for cell in column_cells)
    new_column_letter = (get_column_letter(column_cells[0].column))
    if new_column_length > 0:
        sheet.column_dimensions[new_column_letter].width = new_column_length*1.23
7gs2gvoe

7gs2gvoe8#

sheet.column_dimensions[new_column_letter].width = new_column_length*1.23

上面的代码行将调整列的宽度以达到最佳匹配

piv4azn7

piv4azn79#

def auto_format_cell_width(ws):
    for letter in range(1,ws.max_column):
        maximum_value = 0
        for cell in ws[get_column_letter(letter)]:
            val_to_check = len(str(cell.value))
            if val_to_check > maximum_value:
               maximum_value = val_to_check
        ws.column_dimensions[get_column_letter(letter)].width = maximum_value + 1

相关问题