在只安装了WPS的电脑上,可以使用Python的`win32com`模块调用WPS的API来实现doc转docx。以下是完整代码: ```python import os import win32com.client import zipfile import tempfile import shutil def doc_to_docx(input_folder, output_folder): # 初始化WPS应用 wps = win32com.client.Dispatch("Kwps.Application") wps.Visible = False # 不显示WPS界面 # 确保输出文件夹存在 os.makedirs(output_folder, exist_ok=True) # 遍历输入文件夹 for filename in os.listdir(input_folder): if filename.lower().endswith('.doc'): input_path = os.path.join(input_folder, filename) output_path = os.path.join(output_folder, filename + 'x') try: # 打开doc文件 doc = wps.Documents.Open(input_path) # 保存为docx格式 doc.SaveAs(output_path, FileFormat=12) # 12表示docx格式 doc.Close() # 修复WPS生成的docx内部结构 fix_wps_docx(output_path) print(f"转换成功: {filename}") except Exception as e: print(f"转换失败 {filename}: {str(e)}") # 关闭WPS wps.Quit() def fix_wps_docx(docx_path): # 临时文件夹 temp_dir = tempfile.mkdtemp() try: # 解压原始docx with zipfile.ZipFile(docx_path, 'r') as zip_ref: zip_ref.extractall(temp_dir) # 修复content_types.xml content_types_path = os.path.join(temp_dir, '[Content_Types].xml') with open(content_types_path, 'r', encoding='utf-8') as f: content = f.read() # WPS可能会缺少一些内容类型定义 if 'application/vnd.openxmlformats-officedocument.wordprocessingml' not in content: content = content.replace( '</Types>', '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>') with open(content_types_path, 'w', encoding='utf-8') as f: f.write(content) # 重新压缩为标准的docx with zipfile.ZipFile(docx_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(temp_dir): for file in files: file_path = os.path.join(root, file) arcname = os.path.relpath(file_path, temp_dir) zipf.write(file_path, arcname) finally: # 清理临时文件夹 shutil.rmtree(temp_dir) if __name__ == "__main__": input_folder = r"C:\path\to\your\doc\files" # 替换为你的doc文件夹路径 output_folder = r"C:\path\to\output\folder" # 替换为输出文件夹路径 doc_to_docx(input_folder, output_folder) ``` 代码说明: 1. 使用`win32com`调用WPS的API进行格式转换 2. WPS生成的docx内部结构可能与MS Office不完全一致,代码中包含修复逻辑 3. 转换过程会保留原始文档内容,只调整容器格式 注意事项: 1. 确保电脑已安装WPS Office而非仅WPS文字 2. 需要安装pywin32库:`pip install pywin32` 3. 处理大量文件时,建议分批进行以避免内存问题 4. 转换前最好备份原始文件 [2025-06-04 13:58:03 | AI写代码神器 | 836点数解答]