How to set a fixed width of several columns in sheet by openpyxl?
Question:
I would like to create a for
loop for columns from B to AG for which it will do the width = 3
in xlsx file. I am using openpyxl
library.
Is there any method to get the index of letters from the xlsx sheet
and create such a loop according to it?
# settings for userAccountControl sheet:
sheet_3_name = 'userAccountControl'
flag_col_width = 3
wb_master[sheet_3_name].column_dimensions['B'].width = flag_col_width
...
...
wb_master[sheet_3_name].column_dimensions['AG'].width = flag_col_width
Answers:
You can start by making a list of all possible column letters in Excel ('A'
to 'XFD'
) then make a slice/loop based on the range of columns you need to set width for.
To make this out, you can use openpyxl.utils.cell.get_column_letter
:
from openpyxl.utils.cell import get_column_letter
col_xl = [get_column_letter(idx) for idx in range(1, 16384+1)] #16384 is Excel's limit
start_col, end_col = ("B", "AG")
sheet_3_name = 'userAccountControl'
flag_col_width = 3
for col in col_xl[col_xl.index(start_col):col_xl.index(end_col)+1]:
wb_master[sheet_3_name].column_dimensions[col].width = flag_col_width
I would like to create a for
loop for columns from B to AG for which it will do the width = 3
in xlsx file. I am using openpyxl
library.
Is there any method to get the index of letters from the xlsx sheet
and create such a loop according to it?
# settings for userAccountControl sheet:
sheet_3_name = 'userAccountControl'
flag_col_width = 3
wb_master[sheet_3_name].column_dimensions['B'].width = flag_col_width
...
...
wb_master[sheet_3_name].column_dimensions['AG'].width = flag_col_width
You can start by making a list of all possible column letters in Excel ('A'
to 'XFD'
) then make a slice/loop based on the range of columns you need to set width for.
To make this out, you can use openpyxl.utils.cell.get_column_letter
:
from openpyxl.utils.cell import get_column_letter
col_xl = [get_column_letter(idx) for idx in range(1, 16384+1)] #16384 is Excel's limit
start_col, end_col = ("B", "AG")
sheet_3_name = 'userAccountControl'
flag_col_width = 3
for col in col_xl[col_xl.index(start_col):col_xl.index(end_col)+1]:
wb_master[sheet_3_name].column_dimensions[col].width = flag_col_width