实现功能:转换当前目录下所有xml文件(word另存为xml格式的文件)为word文件
背景:通过cbtg模板引擎生成合同文件时需要创作word模板,将word转xml后可以加入cbtg的文本模板引擎中,因为是xml文件,所以生成的word文件也是xml格式不方便分享传播,故通过python实现将xml文件自动转为docx格式的工具配合cbtg使用
1 | pip install pywin32 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import win32com.client import os def upgrade_word_document(input_path, output_path): # 创建 Word 应用程序对象 word = win32com.client.Dispatch( 'Word.Application' ) word.Visible = False # 不显示 Word 窗口 try : # 打开旧格式的 Word 文档 doc = word.Documents. Open (input_path) # 将文档另存为新格式 doc.SaveAs(output_path, FileFormat = 12 ) # 12 表示 .docx 格式 except Exception as e: print (f "Error upgrading {input_path} to {output_path}: {e}" ) finally : # 关闭文档和 Word 应用程序 doc.Close() word.Quit() # 示例用法 current_directory = os.getcwd() # 获取当前目录下的所有文件 all_files = os.listdir(current_directory) # 过滤出所有的 XML 文件 xml_files = [ file for file in all_files if file .endswith( '.xml' )] # 转换所有的 XML 文件 for xml_file in xml_files: filepath = current_directory + os.path.sep + xml_file.title() print (f '{filepath}' ) file_name, file_extension = os.path.splitext(filepath) out_fil_epath = file_name + ".docx" print (f '{out_fil_epath}' ) upgrade_word_document(filepath, out_fil_epath) |
打包为windows可执行程序,在有xml的目录执行后将所有xml转换为docx
安装pyinstaller
1 | pip install pyinstaller |
1 | pyinstaller - - onefile my_script.py |
下载已经打包好的可执行程序: