一、LibreOffice的下载
下载网址:
主页 | LibreOffice 简体中文官方网站 - 自由免费的办公套件
点击Windows版本下载
安装下载的文件
安装类型选择自定义,下一步修改软件安装的位置,为了不占用C盘空间,我安装在了D盘。
文件类型都没有选择
然后点击下一步直至安装完成
二、配置环境
将下的软件安装路径添加到系统环境变量中,如下所示,替换为你的安装路径。
D:\software\LibreOffice\program\
三、验证是否配置成功
命令行输入 “ soffice --version ”,输出版本号则表示配置成功
四、使用
单个文件转换
import subprocess
import os
def convert_doc_to_docx(doc_path, docx_path):
# 确保 LibreOffice 安装在系统路径中
libreoffice_path = r'D:\software\LibreOffice\program\soffice.exe'
# 检查目标文件夹是否存在
output_dir = os.path.dirname(docx_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 使用 LibreOffice 命令行进行转换
subprocess.run([libreoffice_path, '--headless', '--convert-to', 'docx', doc_path, '--outdir', output_dir])
print(f"转换完成:{doc_path} -> {docx_path}")
# 示例使用
doc_path = r'source.doc'
docx_path = r'target.docx'
convert_doc_to_docx(doc_path, docx_path)
批量转换
import subprocess
import os
def convert_doc_to_docx(doc_path, docx_path):
# 确保 LibreOffice 安装在系统路径中
libreoffice_path = r'D:\software\LibreOffice\program\soffice.exe'
# 检查目标文件夹是否存在
output_dir = os.path.dirname(docx_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 使用 LibreOffice 命令行进行转换
subprocess.run([libreoffice_path, '--headless', '--convert-to', 'docx', doc_path, '--outdir', output_dir])
print(f"转换完成:{doc_path} -> {docx_path}")
def find_all_doc_files(directory):
doc_files = []
# 遍历目录树
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.doc'):
doc_files.append(os.path.join(root, file))
return doc_files
# 示例使用
directory = r'source_dir'
doc_files = find_all_doc_files(directory)
for doc_file in doc_files:
# 替换后缀
docx_file = doc_file.replace('.doc', '.docx')
# 可以新建一个路径保存 docx,防止doc和docx混合
# docx_file = docx_file.replace('','new_folder')
# 自动创建目标文件夹
output_dir = os.path.dirname(docx_file)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
convert_doc_to_docx(doc_file, docx_file)
# print(f'done...{doc_file}')
参考
Windows下安装Libreoffice | 魔众文库系统
windows中安装libreOffice最新版本24.2.4
[1276]LibreOffice安装及使用