欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)word/excel/ppt批量轉(zhuǎn)pdf的示例代碼

 更新時(shí)間:2023年09月05日 08:39:49   作者:夏天是冰紅茶  
這篇文章主要為大家詳細(xì)介紹了如何利用python實(shí)現(xiàn)word、excel、ppt批量轉(zhuǎn)pdf文件,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考下

今天看見了一個(gè)有意思的腳本Python批量實(shí)現(xiàn)Word、EXCLE、PPT轉(zhuǎn)PDF文件

因?yàn)槲移綍r(shí)word用的比較的多,所以深有體會(huì),具體怎么實(shí)現(xiàn)的我們就不討論了,因?yàn)檫@個(gè)去學(xué)了也沒什么提升,不然也不會(huì)當(dāng)作腳本了。這里我將其放入了pyzjr庫中,也方便大家進(jìn)行調(diào)用。

你可以去下載pyzjr:

pip install pyzjr -i https://pypi.tuna.tsinghua.edu.cn/simple

調(diào)用方法:

import pyzjr as pz
# 實(shí)例化對(duì)象
Mpdf = pz.Microsoft2PDF()
# 調(diào)用類的方法
Mpdf.Word2Pdf()  # word -> pdf
Mpdf.Excel2Pdf()  # excel -> pdf
Mpdf.PPt2Pdf()  # ppt -> pdf
Mpdf.WEP2Pdf()  # word,excel,ppt -> pdf

上面就是api的調(diào)用了,統(tǒng)一會(huì)將文件存放在目標(biāo)文件夾下新建的名為pdf文件夾中。

pyzjr中的源碼:

import win32com.client, gc, os
class Microsoft2PDF():
    """Convert Microsoft Office documents (Word, Excel, PowerPoint) to PDF format"""
    def __init__(self,filePath = ""):
        """
        :param filePath: 如果默認(rèn)是空字符,就默認(rèn)當(dāng)前路徑
        """
        self.flagW = self.flagE = self.flagP = 1
        self.words = []
        self.ppts = []
        self.excels = []
        if filePath == "":
            filePath = os.getcwd()
        folder = filePath + '\\pdf\\'
        self.folder = CreateFolder(folder,debug=False)
        self.filePath = filePath
        for i in os.listdir(self.filePath):
            if i.endswith(('.doc', 'docx')):
                self.words.append(i)
            if i.endswith(('.ppt', 'pptx')):
                self.ppts.append(i)
            if i.endswith(('.xls', 'xlsx')):
                self.excels.append(i)
        if len(self.words) < 1:
            print("\n[pyzjr]:No Word files\n")
            self.flagW = 0
        if len(self.ppts) < 1:
            print("\n[pyzjr]:No PPT file\n")
            self.flagE = 0
        if len(self.excels) < 1:
            print("\n[pyzjr]:No Excel file\n")
            self.flagP = 0
    def Word2Pdf(self):
        if self.flagW == 0:
            return 0
        else:
            print("\n[Start Word ->PDF conversion]")
            try:
                print("Open Word Process...")
                word = win32com.client.Dispatch("Word.Application")
                word.Visible = 0
                word.DisplayAlerts = False
                doc = None
                for i in range(len(self.words)):
                    print(i)
                    fileName = self.words[i]  # file name
                    fromFile = os.path.join(self.filePath, fileName)  # file address
                    toFileName = self.changeSufix2Pdf(fileName)  # Generated file name
                    toFile = self.toFileJoin(toFileName)  # Generated file address
                    print("Conversion:" + fileName + "in files...")
                    try:
                        doc = word.Documents.Open(fromFile)
                        doc.SaveAs(toFile, 17)
                        print("Convert to:" + toFileName + "file completion")
                    except Exception as e:
                        print(e)
                print("All Word files have been printed")
                print("End Word Process...\n")
                doc.Close()
                doc = None
                word.Quit()
                word = None
            except Exception as e:
                print(e)
            finally:
                gc.collect()
    def Excel2Pdf(self):
        if self.flagE == 0:
            return 0
        else:
            print("\n[Start Excel -> PDF conversion]")
            try:
                print("open Excel Process...")
                excel = win32com.client.Dispatch("Excel.Application")
                excel.Visible = 0
                excel.DisplayAlerts = False
                wb = None
                ws = None
                for i in range(len(self.excels)):
                    print(i)
                    fileName = self.excels[i]
                    fromFile = os.path.join(self.filePath, fileName)
                    print("Conversion:" + fileName + "in files...")
                    try:
                        wb = excel.Workbooks.Open(fromFile)
                        for j in range(wb.Worksheets.Count):  # Number of worksheets, one workbook may have multiple worksheets
                            toFileName = self.addWorksheetsOrder(fileName, j + 1)
                            toFile = self.toFileJoin(toFileName)
                            ws = wb.Worksheets(j + 1)
                            ws.ExportAsFixedFormat(0, toFile)
                            print("Convert to:" + toFileName + "file completion")
                    except Exception as e:
                        print(e)
                # 關(guān)閉 Excel 進(jìn)程
                print("All Excel files have been printed")
                print("Ending Excel process...\n")
                ws = None
                wb.Close()
                wb = None
                excel.Quit()
                excel = None
            except Exception as e:
                print(e)
            finally:
                gc.collect()
    def PPt2Pdf(self):
        if self.flagP == 0:
            return 0
        else:
            print("\n[Start PPT ->PDF conversion]")
            try:
                print("Opening PowerPoint process...")
                powerpoint = win32com.client.Dispatch("PowerPoint.Application")
                ppt = None
                for i in range(len(self.ppts)):
                    print(i)
                    fileName = self.ppts[i]
                    fromFile = os.path.join(self.filePath, fileName)
                    toFileName = self.changeSufix2Pdf(fileName)
                    toFile = self.toFileJoin(toFileName)
                    print("Conversion:" + fileName + "in files...")
                    try:
                        ppt = powerpoint.Presentations.Open(fromFile, WithWindow=False)
                        if ppt.Slides.Count > 0:
                            ppt.SaveAs(toFile, 32)
                            print("Convert to:" + toFileName + "file completion")
                        else:
                            print("Error, unexpected: This file is empty, skipping this file")
                    except Exception as e:
                        print(e)
                print("All PPT files have been printed")
                print("Ending PowerPoint process...\n")
                ppt.Close()
                ppt = None
                powerpoint.Quit()
                powerpoint = None
            except Exception as e:
                print(e)
            finally:
                gc.collect()
    def WEP2Pdf(self):
        """
        Word, Excel and PPt are all converted to PDF.
        If there are many files, it may take some time
        """
        print("Convert Microsoft Three Musketeers to PDF")
        self.Word2Pdf()
        self.Excel2Pdf()
        self.PPt2Pdf()
        print(f"All files have been converted, you can find them in the {self.folder}")
    def changeSufix2Pdf(self,file):
        """將文件后綴更改為.pdf"""
        return file[:file.rfind('.')] + ".pdf"
    def addWorksheetsOrder(self,file, i):
        """在文件名中添加工作表順序"""
        return file[:file.rfind('.')] + "_worksheet" + str(i) + ".pdf"
    def toFileJoin(self, file):
        """將文件路徑和文件名連接為完整的文件路徑"""
        return os.path.join(self.filePath, 'pdf', file[:file.rfind('.')] + ".pdf")

這里我對(duì)原先博主的代碼進(jìn)行了一定的優(yōu)化,使其可供我們調(diào)用。

這是控制臺(tái)打印出來的信息,我們可以發(fā)現(xiàn)在調(diào)用WEP2Pdf時(shí),如果當(dāng)前文件夾中沒有word的文件也能繼續(xù)去轉(zhuǎn)換。 

到此這篇關(guān)于python實(shí)現(xiàn)word/excel/ppt批量轉(zhuǎn)pdf的示例代碼的文章就介紹到這了,更多相關(guān)python pdf內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • PyCharm中如何創(chuàng)建帶有注釋的py文件

    PyCharm中如何創(chuàng)建帶有注釋的py文件

    這篇文章主要介紹了 PyCharm中如何創(chuàng)建帶有注釋的py文件,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2024-08-08
  • Python實(shí)現(xiàn)飛機(jī)大戰(zhàn)項(xiàng)目

    Python實(shí)現(xiàn)飛機(jī)大戰(zhàn)項(xiàng)目

    這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)飛機(jī)大戰(zhàn)項(xiàng)目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • 使用PYTHON創(chuàng)建XML文檔

    使用PYTHON創(chuàng)建XML文檔

    今天想使用python來創(chuàng)建一個(gè)xml文件。找了下資料,發(fā)現(xiàn)資料不是很多,基本上都是使用python來解析xml文件的
    2012-03-03
  • Python中NumPy的線性代數(shù)子模塊linalg詳解

    Python中NumPy的線性代數(shù)子模塊linalg詳解

    這篇文章主要介紹了Python中NumPy的線性代數(shù)子模塊linalg詳解,NumPy 的線性代數(shù)子模塊linalg提供了 20 余個(gè)函數(shù),用于求解行列式、逆矩陣、特征值、特征向量,以及矩陣分解等,需要的朋友可以參考下
    2023-08-08
  • Python使用itertools模塊實(shí)現(xiàn)排列組合功能示例

    Python使用itertools模塊實(shí)現(xiàn)排列組合功能示例

    這篇文章主要介紹了Python使用itertools模塊實(shí)現(xiàn)排列組合功能,涉及Python基于itertools模塊product、permutations與combinations_with_replacement方法進(jìn)行排列、組合等相關(guān)操作實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2018-07-07
  • Python中如何快速解析JSON對(duì)象數(shù)組

    Python中如何快速解析JSON對(duì)象數(shù)組

    由于瀏覽器可以迅速地解析JSON對(duì)象,它們有助于在客戶端和服務(wù)器之間傳輸數(shù)據(jù),本文將描述如何使用Python的JSON模塊來傳輸和接收J(rèn)SON數(shù)據(jù)
    2023-09-09
  • Python寫的Discuz7.2版faq.php注入漏洞工具

    Python寫的Discuz7.2版faq.php注入漏洞工具

    這篇文章主要介紹了Python寫的Discuz7.2版faq.php注入漏洞工具,全自動(dòng)的一款注入工具,針對(duì)Discuz7.2版,需要的朋友可以參考下
    2014-08-08
  • Tensorflow實(shí)現(xiàn)卷積神經(jīng)網(wǎng)絡(luò)的詳細(xì)代碼

    Tensorflow實(shí)現(xiàn)卷積神經(jīng)網(wǎng)絡(luò)的詳細(xì)代碼

    這篇文章主要為大家詳細(xì)介紹了Tensorflow實(shí)現(xiàn)卷積神經(jīng)網(wǎng)絡(luò)的詳細(xì)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • Django 日志配置按日期滾動(dòng)的方法

    Django 日志配置按日期滾動(dòng)的方法

    今天小編就為大家分享一篇Django 日志配置按日期滾動(dòng)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • 使用python制作一個(gè)截圖小工具

    使用python制作一個(gè)截圖小工具

    這篇文章主要討論了我們?nèi)绾问褂肞ython編程語言進(jìn)行截圖,我們看到了如何使用pyautogui 模塊與save() 函數(shù)和其他模塊,如NumPy 和OpenCV ,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下
    2023-12-12

最新評(píng)論