Python批量将.xlsx文件转为.xls文件

您所在的位置:网站首页 怎么打开xlsx Python批量将.xlsx文件转为.xls文件

Python批量将.xlsx文件转为.xls文件

2023-02-14 19:34| 来源: 网络整理| 查看: 265

工作需要,需要向xls文件里写入数据。由于xlrd\xlwt写入的数据不带格式,只好把xls模板先转为xlsx格式,用openpyxl批量写入完后再批量转为xls。 百度找的转换实例,实际应用时生成的xls文件打开总提示格式不一致或者干脆程序卡死。

 

为了解决这个问题,翻了半天资料。最终解决了,特此记录一下。

 

首先,我先把python升级到64位最新版,然后下载了win32的64位最新版。 其次,把office也换成了64位。 最后,在代码中加入了

xlApp.Visible = FalsexlApp.DisplayAlerts = False

至此,在转换xls文件时,终于不会卡死,可以成功转换了。   以下是代码 .xlsx文件转为.xls文件:

 

import win32com.client as win32def transform_xls(_input_path, _output_path):# 需要转换的文件路径input_path = _input_path# 转换完后输出的路径output_path = _output_path# 遍历需要转换的文件夹下面所有的文件file_list = os.listdir(input_path)# 获取遍历完的文件数量num = len(file_list)# 打印文件数量print(num)# 遍历文件for i in range(num):# 将文件和格式分开file_name = os.path.splitext(file_list[i])# 打印分开后的列表print(file_name)# 当遍历到的文件格式为'.xlsx'时if file_name[1] == '.xlsx':# 得到要转换的文件transfile1 = input_path + file_list[i]# 转换完需要输出的文件transfile2 = output_path + file_name[0]# 打印要转换的文件print('transfile1:'+ str(transfile1))# 使用win32操作excelxlApp = win32.gencache.EnsureDispatch('Excel.Application')# 后台运行, 不显示,不警告# 不写这个会卡死……注意Python、win32需要保持一致。比如我的都是64位的xlApp.Visible = FalsexlApp.DisplayAlerts = False# 打开要转换的excelxls = xlApp.Workbooks.Open(transfile1)# 将需要转换的excel另存为xls格式。 56为xlsxls.SaveAs(transfile2 + '.xls', FileFormat=56)# 关闭excel文件xls.Close()# 退出进程xlApp.Application.Quit()if __name__=='__main__':#待转换文件所在目录input_path = "E:\\Program Files\\桌面\\intput\\"#转换文件存放目录output_path = "E:\\Program Files\\桌面\\intput\\output\\"transform_xls(input_path , output_path)

 

 

参考资料:

Python-批处理.xlsx文件与.xls文件相互转换 https://blog.csdn.net/zkw_1998/article/details/103972386

XlFileFormat 枚举 (Excel) | Microsoft Docs https://docs.microsoft.com/zh-cn/office/vba/api/excel.xlfileformat

python转xlsx为xls 或重新保存xls https://blog.csdn.net/nongcunqq/article/details/113369533

python-win32操作excel的一些特殊功能 - Maple_feng - 博客园 https://www.cnblogs.com/angelyan/p/13094204.html



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3