文档格式批量转换-LibreOffice安装及使用(Windows)

一、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安装及使用

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Billie使劲学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值