需要安装pywin32模块
pip install pywin32
主程序:
import win32com.client as win32 import os.path import glob class Format(): """用于文件转换的类""" def __init__(self): self.excel = win32.gencache.EnsureDispatch('Excel.Application') def xlsx2xls(self, xlsx_path, xls_path): """ 07版本excel转成03版本,多文件转换 :param xlsx_path: 07路径 :param xls_path: 03路径 :return: """ path_list = glob.glob(xlsx_path + '\*.xlsx') # 获取文件夹下所有xlsx for file in path_list: filename = os.path.basename(file).replace('.xlsx', '.xls') # 获取文件名 wb = self.excel.Workbooks.Open(file) wb.SaveAs(xls_path + '\' + filename, FileFormat=56) # xls为56 wb.Close() self.excel.Application.Quit() print('xlsx2xls转换完成') def xlsx2xls_single(self, xlsx_path, xls_path): """ excel 单个文件转换 :param xlsx_path: 07版本 :param xls_path: 03版本 :return:03版本文件路径 """ try: filename = os.path.basename(xlsx_path).replace('.xlsx', '.xls') # 获取文件名 wb = self.excel.Workbooks.Open(xlsx_path) xls_path = os.path.dirname(xlsx_path) xls_path = xls_path.replace('/', '\') save_path = xls_path+'\'+filename wb.SaveAs(save_path, FileFormat=56) # xls为56 wb.Close() self.excel.Application.Quit() print('xlsx2xls转换完成') except Exception as e: wb.Close() self.excel.Application.Quit() print(e) return save_path if __name__ == '__main__': test = Format() test.xlsx2xls_single(xlsx_path=r'E:TestFileAutoReport_TestCD新生成的报告2020-11-21311671.xlsx', xls_path=r"E:TestFileAutoReport_TestCD新生成的报告2020-11-21")
ps: 该模块使用的路径格式分隔符为“\”