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

批量将.xls文件转换为.xlsx文件时遇代码错误求排查

批量转换桌面test文件夹中xls文件为xlsx的代码问题及修正

原尝试编写代码批量遍历桌面test文件夹中的Excel .xls文件并转换为.xlsx文件,但代码逻辑混乱,且出现错误:TypeError: listdir: path should be string, bytes, os.PathLike or None, not list。修改后的代码仍存在多处问题,以下是问题分析及修正方案:

修改后的问题代码

file_path = Path.home().joinpath("Desktop", "test")
excel = win32.gencache.EnsureDispatch('Excel.Application')

if __name__ == "__main__":    
    while True:        
        the_path = (str(file_path) + str("\\"))        
        print(the_path)        
        os.chdir(the_path)

        xls_files = os.listdir('.')        
        print(xls_files)

        for downloadedFile in listdir(xls_files):            
            if downloadedFile.endswith('.xls'):                
                wb = excel.Workbooks.Open(xls_files)                
                pyexcel.save_book_as(downloadedFile, FileFormat = 51)                
                downloadedFile.Close()                
                downloadedFile.Save()        
        excel.Application.Quit()  

问题分析

  • listdir(xls_files)参数错误:os.listdir()要求传入路径字符串,而xls_files是文件列表,直接传入触发类型错误;
  • 路径拼接冗余易出错:Path对象本身可直接转为字符串,无需手动拼接反斜杠;
  • 对象调用逻辑混乱:downloadedFile是文件名字符串,不能调用.Close()/.Save(),这些方法属于Excel工作簿对象;excel.Workbooks.Open()需传入具体文件路径,而非文件列表;
  • 多库混用逻辑冲突:同时用win32com和pyexcel操作Excel,逻辑冗余混乱;
  • 无意义循环:此处不需要while True无限循环,遍历一次文件夹即可;
  • 缺失必要导入:代码未导入os、pathlib.Path、win32com.client等依赖,直接运行会报错。

修正后的代码(基于win32com实现)

import os
from pathlib import Path
import win32com.client as win32

def convert_xls_to_xlsx(folder_path):
    # 初始化Excel应用,后台静默运行
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    excel.Visible = False
    excel.DisplayAlerts = False

    # 遍历目标文件夹,筛选xls文件(排除Excel临时文件)
    for filename in os.listdir(folder_path):
        if filename.endswith('.xls') and not filename.startswith('~$'):
            xls_full_path = os.path.join(folder_path, filename)
            # 生成对应的xlsx文件名及路径
            xlsx_filename = os.path.splitext(filename)[0] + '.xlsx'
            xlsx_full_path = os.path.join(folder_path, xlsx_filename)

            # 打开xls文件并另存为xlsx格式
            wb = excel.Workbooks.Open(xls_full_path)
            wb.SaveAs(xlsx_full_path, FileFormat=51)  # 51对应标准xlsx格式
            wb.Close()

    # 退出Excel应用,释放资源
    excel.Quit()

if __name__ == "__main__":
    target_folder = Path.home().joinpath("Desktop", "test")
    convert_xls_to_xlsx(str(target_folder))

代码说明

  • 封装独立转换函数,逻辑清晰易维护;
  • 自动排除Excel临时文件(以~$开头),避免读取错误;
  • 完整拼接文件路径,确保Excel能正确定位文件;
  • 关闭Excel可视界面和弹窗提示,实现静默批量转换;
  • 严格使用Excel工作簿对象调用方法,逻辑严谨无错误。

内容的提问来源于stack exchange,提问作者Jose Daniel Rojas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:40:25