需要本地安装WPS ,调用 WPS Office 的 COM 接口
[Python] 纯文本查看 复制代码 import os
import win32com.client
from pathlib import Path
def convert_wps_to_docx_using_wps(wps_file_path, docx_file_path=None):
"""
使用本地安装的WPS Office将.wps文件转换为.docx文件
"""
try:
# 启动WPS应用
wps = win32com.client.Dispatch("Kwps.Application")
# 如果想静默转换,不显示界面,可以设置Visible为False
wps.Visible = False
# 打开WPS文件
doc = wps.Documents.Open(os.path.abspath(wps_file_path))
# 如果未指定输出路径,则使用原文件名和路径,仅修改后缀
if docx_file_path is None:
docx_file_path = str(Path(wps_file_path).with_suffix('.docx'))
# 保存为DOCX格式
# 参数说明:FileName=输出路径, FileFormat=16 代表docx格式
# 更多FileFormat值:0: .doc (97-2003), 16: .docx, 12: .pdf 等
doc.SaveAs2(os.path.abspath(docx_file_path), FileFormat=16)
# 关闭文档和WPS应用
doc.Close()
wps.Quit()
print(f"转换成功: {wps_file_path} -> {docx_file_path}")
return True
except Exception as e:
print(f"转换失败 {wps_file_path}: {e}")
return False
def batch_convert_wps_folder(folder_path, output_folder=None):
"""
批量转换一个文件夹内所有的.wps文件
"""
folder = Path(folder_path)
if output_folder:
output_dir = Path(output_folder)
output_dir.mkdir(parents=True, exist_ok=True)
else:
output_dir = folder / "converted_docx"
output_dir.mkdir(exist_ok=True)
# 查找所有.wps文件
wps_files = list(folder.glob("*.wps"))
if not wps_files:
print(f"在文件夹 {folder} 中未找到.wps文件")
return
print(f"找到 {len(wps_files)} 个.wps文件,开始转换...")
success_count = 0
for wps_file in wps_files:
output_path = output_dir / f"{wps_file.stem}.docx"
if convert_wps_to_docx_using_wps(str(wps_file), str(output_path)):
success_count += 1
print(f"批量转换完成!成功:{success_count}/{len(wps_files)}")
# 使用示例
if __name__ == "__main__":
# 单个文件转换
# convert_wps_to_docx_using_wps(r"C:\test\document.wps")
# 批量转换整个文件夹
batch_convert_wps_folder(r"D:\我的文档\WPS文件", r"D:\我的文档\转换后的DOCX")
|