python 转换word,excel至PDF

该博客介绍了如何使用Python的docx2pdf和win32com库来批量转换Word和Excel文件到PDF格式。具体步骤包括安装必要的库,定义转换函数,并遍历指定目录下的文件进行转换。在Word转换中,直接调用docx2pdf库完成转换;在Excel转换中,通过win32com与Excel应用交互进行转换,但目前存在未解决的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

word转PDF

主要是通过docx2pdf这个工具包实现的,安装pip install docx2pdf.

execel转PDF

目前是通过win32com这个包进行转换(目前暂未走通)
遇到以下问题:
在这里插入图片描述
整体代码:

import os
import xlrd
import time
import pythoncom
from docx2pdf import convert
from win32com.client import Dispatch, constants, gencache, DispatchEx

def convert_word_to_pdf(file_name):
    word_path, word_name = os.path.split(file_name)
    pdf_name = os.path.splitext(word_name)[0] + '.pdf'
    save_pdf_path = os.path.join(word_path, pdf_name)
    convert(file_name, save_pdf_path)

def convert_excel_to_pdf(file_name):
    excel_file = xlrd.open_workbook(file_name)
    sheetnum = len(excel_file.sheets())
    pythoncom.CoInitialize()
    xlApp = DispatchEx("Excel.Application")
    xlApp.Visible = False
    xlApp.DisplayAlerts = 0
    books = xlApp.Workbooks.Open(file_name)
    excel_name = os.path.splitext(os.path.split(file_name)[1])[0]
    pdf_save_path = os.path.split(file_name)[0]
    for i in range(1, sheetnum):
        sheetName = books.Sheets(i).Name
        xlSheet = books.Worksheets(sheetName)
        name = excel_name + '_' + sheetName + '.pdf'
        exportfile = os.path.join(pdf_save_path, name)
        xlSheet.ExportAsFixedFormat(0, exportfile)
        time.sleep(3)
    books.Close(False)
    xlApp.Quit()

def load_path_get_file(file_path):
    files = os.listdir(file_path)
    is_word_str = ['.docx', '.doc']
    is_excel_str = ['.xlsx', '.csv', '.xls']
    word_file_list = []
    excel_file_list = []
    for file in files:
        if os.path.splitext(file)[1] in is_word_str:
            word_file = os.path.join(file_path, file)
            word_file_list.append(word_file)
        elif os.path.splitext(file)[1] in is_excel_str:
            excel_file = os.path.join(file_path, file)
            excel_file_list.append(excel_file)

    return word_file_list, excel_file_list

if __name__ == '__main__':
    file_path = 'D:/test'
    word_files_list, excel_files_list = load_path_get_file(file_path)
    # 转换word为pdf
    if word_files_list:
        for w_file in word_files_list:
            convert_word_to_pdf(w_file)

    # 转换excel为pdf
    if excel_files_list:
        print(excel_files_list)
        convert_excel_to_pdf(r'D:\test\1.xlsx')
        # for e_file in excel_files_list:
        #     convert_excel_to_pdf(e_file)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值