I am using openpyxl to work with .xlsx
files in Python
.
I have a sample.xlsx
file from which I want to get a list of title fields and column width to use in the file generated by my script.
At first I create a list with column names and their corresponding widths. So I use:
filter_list = {"name": [], "width": []}
row_count = sheet.max_row
for i in range(row_count):
cell = sheet.cell(row, i + 1)
if cell.value:
filter_list["name"].append(cell.value)
filter_list["width"].append(sheet.column_dimensions
[cell.column].width)
value to get column widths and then I set the same value:
if filter_list["width"][i] is not None:
sheet.column_dimensions[cell.column].width = filter_list["width"][i]
It works fine if a particular column has a non-default value (i.e. not None). When I open the output file (on both Mac and Windows) I see that the width of this particular column is the same for both files.
But if one of the columns has ...width = None
in the input file (so the output file have the same None
value for column width parameter) the same column in the output file looks different.
Any ideas on why it happens?
It looks like somewhere in the .xlsx
there is a parameter, which somehow defines what the default width (= None value) is set to.
Is there any way to make both files look the same in terms of column width?
Update: I added a check for width value of None
. I only set the column width parameter for columns that have not None
value. The result is still the same - files are different in terms for default width.
Update 2: I have updated the code to show exactly how I read and set column width.