如何使用openpyxl为Excel表格中B至AG列设置固定宽度?
使用openpyxl批量设置B到AG列的宽度
openpyxl的openpyxl.utils模块提供了列字母与索引互转的工具函数,完美解决你需要的循环批量设置列宽的需求。
实现步骤:
- 导入列字母/索引转换的工具函数
- 将起始列(B)和结束列(AG)转换为对应的数字索引
- 遍历索引范围,将每个索引转回列字母,批量设置列宽
完整代码示例:
from openpyxl import load_workbook from openpyxl.utils import get_column_letter, column_index_from_string # 加载目标工作簿(根据你的实际文件路径调整) wb_master = load_workbook('your_file.xlsx') sheet_3_name = 'userAccountControl' flag_col_width = 3 target_sheet = wb_master[sheet_3_name] # 定义需要设置的列范围 start_col_letter = 'B' end_col_letter = 'AG' # 转换为列索引(B对应2,AG对应33) start_idx = column_index_from_string(start_col_letter) end_idx = column_index_from_string(end_col_letter) # 循环遍历所有目标列,设置宽度 for col_idx in range(start_idx, end_idx + 1): col_letter = get_column_letter(col_idx) target_sheet.column_dimensions[col_letter].width = flag_col_width # 保存修改后的工作簿 wb_master.save('modified_file.xlsx')
补充说明:
column_index_from_string(col_letter):将列字母(如'B'、'AG')转换为数字索引get_column_letter(col_idx):将数字索引转换回列字母- 循环时使用
range(start_idx, end_idx + 1),因为range是左闭右开的写法,加1才能包含结束列的索引
内容的提问来源于stack exchange,提问作者Kubix
相关产品推荐
相关产品推荐

