[PY] Word 处理, 技术选型, Word 转 PDF

1. 安装win32库

python -m pip install pypiwin32

缺点:
仅windows平台,且装有office

优点:
部分API十分灵活,可以直接以微软的API文档进行操作

整体架构

Tables
-- Table
-- Columns
-- Column
-- Cells
-- Cell
-- Rows
-- Row

微软api

word:
https://docs.microsoft.com/en-us/dotnet/ap...

https://docs.microsoft.com/zh-cn/office/vb...

excel:
https://docs.microsoft.com/en-us/dotnet/ap...
https://docs.microsoft.com/zh-cn/office/vb...

详解Row:

注意,当Row有单元格合并,则无法通过 Rows[某行索引] 读取到某行,会报错
解决:通过 Cells(行索引, 列索引) 去读取具体的单元格
注意:行索引与列索引 都是从1开始,对于0的索引与1的索引都是指向同一个

索引如图:

【PY】Word 处理, 技术选型, Word 转 PDF

导出pdf

from win32com.client import Dispatch, constants, gencache

def doc2pdf(input, output):
    w = Dispatch('Word.Application')
    try:
        # 打开文件
        doc = w.Documents.Open(input, ReadOnly=1)
        # 转换文件
        doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF,
                                Item=constants.wdExportDocumentWithMarkup,
                                CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
        return True
    except:
        return False
    finally:
        w.Quit(constants.wdDoNotSaveChanges)

def GenerateSupport():
    gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)

def main():
    input = 'C:\\test\\Word_2_PDF\\Docfile.docx'
    output = 'C:\\test\\Word_2_PDF\\2.pdf'
    # GenerateSupport()
    rc = doc2pdf(input, output)
    if rc:
        print('转换成功')
    else:
        print('转换失败')

if __name__ == '__main__':
    main()

2. comtypes

失败

Traceback (most recent call last):
  File "/Users/kingdelee/PycharmProjects/SIL/src/py/study/toPdf/MyComtypes.py", line 1, in <module>
    from comtypes import client
  File "/usr/local/lib/python3.7/site-packages/comtypes/__init__.py", line 23, in <module>
    from _ctypes import COMError
ImportError: cannot import name 'COMError' from '_ctypes' (/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_ctypes.cpython-37m-darwin.so)
from comtypes import client

class ComTypes:

    def ppt_pdf(self, path):
        # PPT 转 PDF
        pdf_path = path.replace('ppt', 'pdf')  # pdf保存路径 推荐使用绝对路径
        try:
            p = client.CreateObject("PowerPoint.Application")
            ppt = p.Presentations.Open(path)
            ppt.ExportAsFixedFormat(pdf_path, 2, PrintRange=None)
            ppt.Close()
            p.Quit()
        except Exception as e:
            pass

    def word_pdf(self, path):
        # Word转pdf
        pdf_path = path.replace('doc', 'pdf')
        w = client.CreateObject("Word.Application")
        doc = w.Documents.Open(path)
        doc.ExportAsFixedFormat(pdf_path, 17)
        doc.Close()
        w.Quit()

    def excel_pdf(self, path):
        # Excel转pdf
        pdf_path = path.replace('xls', 'pdf')
        xlApp = client.CreateObject("Excel.Application")
        books = xlApp.Workbooks.Open(path)
        books.ExportAsFixedFormat(0, pdf_path)
        xlApp.Quit()

if __name__ == '__main__':
    comty  = ComTypes()
    comty.word_pdf("/Users/kingdelee/Downloads/Word_2_PDF/Docfile.docx")

3. pdfkit pdf 水印

4. python-docx-template

模板方式
官方文档:
https://docxtpl.readthedocs.io/en/latest/#

参考:
https://blog.csdn.net/weixin_42670653/arti...
https://blog.csdn.net/DaShu0612/article/de...

安装:
pip install docxtpl

5. python-docx

优点:不依赖操作系统,跨平台

参考:
https://blog.csdn.net/edogawachia/article/...
https://www.jb51.net/article/143936.htm

5.1 结构说明

docx是以Document为文本,对paragraph、table等重要的结构进行解析

word中某内容是普通的文字,对应用paragraph解析

【PY】Word 处理, 技术选型, Word 转 PDF

word中某内容是表格,即对应用table解析
而table中的一个单元格的内容,实际上也可以看做是一个paragraph

【PY】Word 处理, 技术选型, Word 转 PDF

run作为paragraph的内容对象,一般用来处理内容的新增或者修改

【PY】Word 处理, 技术选型, Word 转 PDF

文本中的样式由style类进行描绘

【PY】Word 处理, 技术选型, Word 转 PDF

然而,font是run中的属性,修改font的时候,需要从run着手

【PY】Word 处理, 技术选型, Word 转 PDF

PT修改字体大小

【PY】Word 处理, 技术选型, Word 转 PDF

5.2 读取文档

document = Document('test.docx')

5.3 读取表格

for table in document.tables

5.4 读取行

for row in table.rows

5.4.1 读取单元格

for cell in row.cells

5.4.2 读取单元格内容

文本:

text = cell.text

如之前所说,cell的内容实际上也是可以由多个paragraph构成的
一般情况下,cell有且只有一个paragraph,paragraph有且只有一个run

paragraph = cell.paragraphs[0]
run = paragraph.runs[0]

5.4.3 替换内容

可以先清除

paragraph = paragraph.clear()
run = paragraph.add_run("新的内容")

5.5 修改字体的大小、型号、颜色

font = run.font
font.size = Pt(15)
font.name = 'SimSun'
font.color.rgb = RGBColor(54,95,145)
font.bold = True
font.underline = True

5.5.1 设置段落文字居中

paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

5.6 单元格与表的关系

【PY】Word 处理, 技术选型, Word 转 PDF

cell = table.cell(0, 1)

5.6.1 添加行、合并单元格

要想在某个单元格下方添加一行
可以使用组合操作,先对table添加行,再进行cell合并操作,实现特定的结构

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 1
yicijohncy

请问一下,上面提到的那个问题cannot import name 'COMError' from '_ctypes'是怎么解决的呢 file

4年前 评论
kingdelee (楼主) 4年前
kingdelee (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!