You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python代码实现Excel列从A迭代到ZZ?

实现Excel列从A到ZZ的迭代调整方案

原代码的问题在于仅使用string.ascii_uppercase遍历单个大写字母(A-Z),无法覆盖AA到ZZ的双字母列标识。以下是两种可行的修改方案:

方法一:根据工作表实际列数动态生成(推荐)

利用openpyxl.utils中的get_column_letter函数,将列号转换为对应的字母标识(1→A,27→AA,702→ZZ),遍历工作表的所有实际列,既灵活又避免无效遍历:

import pandas
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter

book = load_workbook('QualityReview Business-Template.xlsx')

writer = pandas.ExcelWriter('QualityReview Business-Template.xlsx', engine='openpyxl') 
writer.book = book
busi_issue_date.to_excel(writer, "IssueData")
worksheet = book["IssueData"]

# 遍历所有实际列,生成对应字母标识
for col_num in range(1, worksheet.max_column + 1):
    letter = get_column_letter(col_num)
    max_width = 0

    for row_number in range(1, worksheet.max_row + 1):
        cell_value = str(worksheet[f'{letter}{row_number}'].value)
        if len(cell_value) > max_width:
            max_width = len(cell_value)
    # 统一设置列宽,避免重复赋值提升效率
    worksheet.column_dimensions[letter].width = max_width + 1

writer.save()

优化说明:将列宽赋值移到内层循环之外,避免每一行都重复设置,提升代码效率。

方法二:手动生成A到ZZ的所有列标识

如果需要固定遍历A到ZZ的所有列(不管工作表实际列数),可以通过生成单字母+双字母组合实现:

import pandas
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
from string import ascii_uppercase
import itertools

book = load_workbook('QualityReview Business-Template.xlsx')

writer = pandas.ExcelWriter('QualityReview Business-Template.xlsx', engine='openpyxl') 
writer.book = book
busi_issue_date.to_excel(writer, "IssueData")
worksheet = book["IssueData"]

# 生成A-Z + AA-ZZ的所有列标识
cols = list(ascii_uppercase) + [''.join(pair) for pair in itertools.product(ascii_uppercase, repeat=2)]

for letter in cols:
    max_width = 0
    # 仅处理工作表中存在的列,避免索引错误
    if letter not in worksheet.column_dimensions:
        continue
    for row_number in range(1, worksheet.max_row + 1):
        cell_value = str(worksheet[f'{letter}{row_number}'].value)
        if len(cell_value) > max_width:
            max_width = len(cell_value)
    worksheet.column_dimensions[letter].width = max_width + 1

writer.save()

注意:添加了列存在性判断,避免遍历到工作表中不存在的列时抛出错误。

内容的提问来源于stack exchange,提问作者user3044949

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:10:03