简体   繁体   中英

How to calculate the max string length value in excel sheet cell range using openpyxl?

I have tried so many different ways to calculate the max string length value in range of cells that have string values. The goal is to get the max string length and then set each column width to this max string length. The code below is implemented after string values are entered in to the range of cells but some rows will not have any values entered in. The code I have is suppose to skip any row if it's first cell value isn't a string. The values I enter into the excel range goes beyond the first cell so I just have to check value of each row's first cell to know that row doesn't have any values. I have tried to use iter_rows() and iter_cols() in ways similar to online examples to accomplish this but I haven't been able to find a solution. The error I'm getting is for index in range(len(col)): TypeError: object of type 'int' has no len() . The module I'm using is openpyxl and I have set data_only = True within my load_workbook statement. Also, col is referencing a list that contains the letters of alphabet up to the last column that has any values.

Can anyone help or give me any suggestions?

    maxLen = 0
    for row in range(1, ws.max_row):
        if type(ws.cell(row, 1).value) == str:

            for col in range(1, ws.max_column - 1):
                if len(ws.cell(row, col).value) > len(ws.cell(row, col + 1).value):
                    maxLen = len(ws.cell(row, col).value)
                else:
                    maxLen = len(ws.cell(row, col + 1).value)
        else:
            continue

    for index in range(len(col)):
        ws.column_dimensions[f'{col[index]}'].width = maxLen

Excel has this weird calculation it forces you to do between pixels and points if you're looking to be that precise, and there are functions on here to do that conversion for you but if you want to make the columns fit an entire string there is a shorter way.

Private Sub Workbook_Open()

    Dim ws as Worksheet : set ws = ThisWorkbook.Sheets("Sheet1")
    ws.Columns("A:Z").Autofit

End Sub

You could create an excel template file with this sub in it that openpyxl uses when creating new files.

wb = load_workbook('template.xltm', keep_vba=True)
wb.save('new_document.xlsm')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM