在Python中doc转docx,xls转xlsx,ppt转pptx(Windows)

在Python中doc转docx,xls转xlsx,ppt转pptx(Windows)

说明:

  • 首次发表日期:2024-07-18
  • 参考pypi包: doc2docx

缘起

我们一般使用Python开发RAG应用,或者使用基于Python开发的开源RAG工具,比如Dify。然而由于Python中对.doc.ppt格式的文件支持不够好,通常我们需要将文件格式转换为.docx.pptx,以便之后RAG对这些文档进行解析。

通常,我们可以会直接打开Office软件,手动将文件另存为.docx或者.pptx格式。这个过程,我们可以使用Python进行自动化。

在开始之前,首先需要确保微软的Office软件有正常安装好。

依赖

安装pywin32包:

pip install pywin32

导入依赖库:

import win32com.client
from pathlib import Path

doc转docx

参考: https://learn.microsoft.com/en-us/office/vba/api/word.saveas2

def doc2docx(input_filepath, output_filepath, keep_active = True):
    input_filepath = Path(input_filepath).resolve()
    output_filepath = Path(output_filepath).resolve()
    word_app = win32com.client.Dispatch("Word.Application")
    doc = word_app.Documents.Open(str(input_filepath))
    try:
        doc.SaveAs2(str(output_filepath), FileFormat=16)
    except:
        raise
    finally:
        doc.Close(0)
    
    if not keep_active:
        word_app.Quit()

ppt转pptx

参考:

  • https://learn.microsoft.com/en-us/office/vba/api/powerpoint.presentations.open
  • https://learn.microsoft.com/en-us/office/vba/api/powerpoint.presentation.saveas
def ppt2pptx(input_filepath, output_filepath, keep_active = True):    
    input_filepath = Path(input_filepath).resolve()
    output_filepath = Path(output_filepath).resolve()
    ppt_app = win32com.client.Dispatch("Powerpoint.Application")
    presentation = ppt_app.Presentations.Open(str(input_filepath), 0, 0, 0)
    try:
        presentation.SaveAs(str(output_filepath), FileFormat=24)
    except:
        raise
    finally:
        presentation.Close()
    
    if not keep_active:
        ppt_app.Quit()

xls转xlsx

参考:

  • https://learn.microsoft.com/en-us/office/vba/api/excel.xlfileformat
  • https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.saveas
def convert_xls2xlsx(input_filepath, output_filepath, keep_active = True):
    input_filepath = Path(input_filepath).resolve()
    output_filepath = Path(output_filepath).resolve()
    excel_app = win32com.client.Dispatch("Excel.Application")
    sheet = excel_app.Workbooks.Open(str(input_filepath))
    try:
        sheet.SaveAs(str(output_filepath), FileFormat=51)
    except:
        raise
    finally:
        sheet.Close(0)
    
    if not keep_active:
        excel_app.Quit()
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值