使用python完成文档格式转换有很多库可以用,例如pdfkit可实现html转换为pdf,mammoth可实现word转html等文件格式的转换,这些库有些转换效果不错,有些库转换后会发生格式丢失等问题,转换效果差强人意,而且需要学习的新知识较多。考虑到word应用程序本身即可打开和保存docx、html、txt等多种格式文件,因此,如果可以在python代码中直接操作word来打开和另存文件,这显然是最方便的文档格式转换方案。幸运的是,win32com库给我们提供了在python代码中操作word的功能。这样,我们只需掌握VBA的Documents.Open()方法和Document.SaveAs2()方法,就可以在win32com库的支持下轻松完成word支持的文档格式之间的相互转换。以下介绍使用win32com库操作word转换文档格式的方法。

由于word默认在打开非默认格式文档时会打开文件转换对话框要求确认,为了防止确认文件格式转换中断python代码的执行,在正式写代码之前我们先要打开word选项,确认下图的设置中“打开时确认文件格式转换”选项是否取消了选中。

Python把html转pdf python html转word文档_Word

 准备工作完成后,可以开始编写转换文件格式的代码了:

import win32com # 导入win32com库,pip install pypiwin32
from win32com.client import constants as wc # 导入相关常量


def convert_format(word, source_file, dest_file, source_format, dest_format):
    '''
        文件格式转换函数
        Args:
            word:word应用程序对象
            source_file:待转换格式的源文件,不在当前目录需带文件路径
            dest_file:转换后的目标文件,可指定路径,未指定路径则保存在当前目录
            source_format:源文件格式,参见VBA文档WdOpenFormat枚举值
            dest_format:目标文件格式,参见VBA文档WdSaveFormat枚举值
    '''

    # 调用VBA对象Documents的Open方法打开source_file,有必要的话传入文件绝对路径
    doc = word.Documents.Open(FileName = source_file, Format=source_format)
    try:
        # 对网页文件进行一些设定,具体含义可访问https://docs.microsoft.com/zh-cn/office/vba/api/查阅VBA文档
        word.ActiveDocument.WebOptions.RelyOnCSS = 1
        word.ActiveDocument.WebOptions.OptimizeForBrowser = 1
        word.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
        word.ActiveDocument.WebOptions.OrganizeInFolder = 0
        word.ActiveDocument.WebOptions.UseLongFileNames = 1
        word.ActiveDocument.WebOptions.RelyOnVML = 0
        word.ActiveDocument.WebOptions.AllowPNG = 1
        # 将文件另存为目标文件格式,完成格式转换
        word.ActiveDocument.SaveAs2( FileName =dest_file, FileFormat = dest_format)
        # 完成转换后原document对象已经指向目标格式文件
        print('完成了文件{0}的转换'.format(doc.Name))
    finally:
        # 关闭文档
        doc.Close()

source_file = 'test.html'
dest_file = 'test.docx'


# 打开word应用程序
#word = win32com.client.Dispatch('Word.Application')
# 或者使用下面的方法,使用启动独立的进程:
# word = win32com.client.DispatchEx('Word.Application')
# 如果文件格式参数传入VBA常量出错,应当用下面的方法打开word应用程序
word = win32com.client.gencache.EnsureDispatch('Word.Application')

# 后台运行,不显示,不警告
word.Visible = 0
word.DisplayAlerts = 0

# 调用文件格式转换函数,将一个html文件转换为docx文件。
convert_format(word, source_file, dest_file, 
        source_format = wc.wdOpenFormatWebPages,
        dest_format = wc.wdFormatDocumentDefault)

# 退出word
word.Quit()

在使用win32com库操作word时应当注意VBA函数第一个字母通常大写,与python通用规范有所区别,不要出现函数名称输入错误。以下是复制Documents对象的Open()方法和Document对象的SaveAs2()方法的文档,以供灵活运用以上代码时参考:

Documents.Open 方法 (Word)

打开指定的文档并将其添加到 Documents 集合。 返回一个 Document 对象。

语法

expression.Open (FileName、 ConfirmConversions、 ReadOnly、 AddToRecentFiles、 PasswordDocument、 PasswordTemplate、 Revert、 WritePasswordDocument、 WritePasswordTemplate、 Format、 Encoding、 Visible、 OpenConflictDocument、 OpenAndRepair、 DocumentDirection、 NoEncodingDialog)

expression 是必需的。 一个Documents对象变量。

参数

名称

必需/可选

数据类型

说明

FileName

必需

Variant

文档名(可包含路径)。

ConfirmConversions

可选

Variant

True 显示 转换文件 对话框中,如果该文件不是 Microsoft Word 格式。

ReadOnly

可选

Variant

为 True,则以只读方式打开文档。 此参数不会覆盖已保存文档的只读推荐设置。 例如,如果在打开只读推荐设置的情况下保存文档,则将 ReadOnly 参数设置为 False 将不会导致文件以读/写方式打开。

AddToRecentFiles

可选

Variant

 要将文件名添加到列表中最近使用的文件在 文件 菜单的底部。

PasswordDocument

可选

Variant

打开文档时所需的密码。

PasswordTemplate

可选

Variant

打开模板时所需的密码。

Revert

可选

Variant

控制如果 FileName 是打开文档的名称会进行什么操作。 为 True,则放弃对打开文档的任何未保存更改并重新打开文件。 为 False,则激活打开的文档。

WritePasswordDocument

可选

Variant

用于保存文档更改的密码。

WritePasswordTemplate

可选

Variant

用于保存模板更改的密码。

Format

可选

Variant

用于打开文档的文件转换器。 可为以下 WdOpenFormat 常量之一。 默认值为 wdOpenFormatAuto。 若要指定外部文件格式,请将 OpenFormat 属性应用于 FileConverter 对象,以确定要与此参数一起使用的值。

Encoding

可选

Variant

当你查看保存的文档时 Microsoft Word 所使用的文档编码(代码页或字符集)。 可以是任何有效的 MsoEncoding 常量。 要查看有效 MsoEncoding 常量的列表,请参阅“Visual Basic 编辑器”中的“对象浏览器”。 默认值是系统代码页。

Visible

可选

Variant

如此 如果在可见窗口中打开文档。 默认值为 True 。

OpenConflictDocument

可选

Variant

指定是否打开具有脱机冲突的文档的冲突文件。

OpenAndRepair

可选

Variant

如果该属性为 True ,则修复文档,以防止文档毁坏。

DocumentDirection

可选

WdDocumentDirection

表示文档中的横排文字。 默认值为 wdLeftToRight

NoEncodingDialog

可选

Variant

为 True,如果无法识别文本编码,则跳过显示 Word 所显示的“编码”对话框。 默认值为 False

返回值

Document对象

Document.SaveAs2 方法 (Word)

使用新的名称或格式保存指定的文档。 此方法的一些参数与 “另存为” 对话框(“文件” 选项卡)中的选项相对应。

语法

expression.SaveAs2_FileName_ , _FileFormat_ , _LockComments_ , _Password_ , _AddToRecentFiles_ , _WritePassword_ , _ReadOnlyRecommended_ , _EmbedTrueTypeFonts_ , _SaveNativePictureFormat_ , _SaveFormsData_ , _SaveAsAOCELetter_ , _Encoding_ , _InsertLineBreaks_ , _AllowSubstitutions_ , _LineEnding_ , _AddBiDiMarks_ , _CompatibilityMode_ )

expression:一个document对象变量

参数

名称

必需/可选

数据类型

说明

FileName

可选

Variant

文档的名称。 默认值为当前文件夹和文件名。 如果从未保存过文档,将使用默认名称(例如,Doc1.doc)。 如果已经存在具有指定文件名的文档,则覆盖该文档,并且在覆盖前不提示用户。

FileFormat

可选

Variant

文档的保存格式。 可以是任意 WdSaveFormat 常量。 若要以另一种格式保存文档,请为 FileConverter 对象的 SaveFormat

LockComments

可选

Variant

如果为 True,则锁定文档注释。 默认值为 False

Password

可选

Variant

用于打开文档的密码字符串。 (请参阅下面的“备注”。)

AddToRecentFiles

可选

Variant

如果为 True,则将文档添加到“文件”菜单上最近使用的文件列表中。 默认值为 True

WritePassword

可选

Variant

用于保存文档更改的密码字符串。 (请参阅下面的“备注”。)

ReadOnlyRecommended

可选

Variant

如果为 True,则每次打开文档时,Microsoft Word 都将建议采用只读方式。 默认值为 False

EmbedTrueTypeFonts

可选

Variant

如果为 True,则 TrueType 字体随文档一起保存。 如果省略,则 EmbedTrueTypeFonts 参数将假定为 EmbedTrueTypeFonts

SaveNativePictureFormat

可选

Variant

如果该属性值为 True,则对于从其他系统平台(如 Macintosh)导入的图形,只保存其 Microsoft Windows 版本。

SaveFormsData

可选

Variant

如果为 True,则将用户在窗体中输入的数据保存为记录。

SaveAsAOCELetter

可选

Variant

如果文档包含附加的邮件,当该属性值为 True 时,将文档存为 AOCE 信函(同时保存邮件)。

Encoding

可选

Variant

用于另存为编码文本文件的文档的代码页或字符集。 默认为系统代码页。 不能将所有 MsoEncoding 常量

InsertLineBreaks

可选

Variant

在将文档保存为文本文件时,如果该属性值为 True,则在每一行文本后插入换行符。

AllowSubstitutions

可选

Variant

将文档保存为文本文件时,如果该属性值为 True,则 Word 可以将一些符号替换为相似的文本。 例如,将版权符号显示为 (c)。 默认值为 False

LineEnding

可选

Variant

Word 在另存为文本文件的文档中标记换行符和分段符的方式。 可以是下列 WdLineEndingType 常量之一: wdCRLF (或 wdCROnly) wdCROnly

AddBiDiMarks

可选

Variant

如果为 True,则为输出文件添加控制符,以保留原始文档中文本的双向版式。

CompatibilityMode

可选

Variant

打开文档时,Word 使用的兼容性模式。 WdCompatibilityMode 常量。


重要说明

默认情况下,如果没有为此参数指定任何值,则 Word 输入值 0,这会指定应保留文档的当前兼容性模式。

返回值

下面是WdSaveFormat枚举值:

名称


说明

wdFormatDocument

0

Microsoft Office Word 97 - 2003 二进制文件格式.

wdFormatDOSText

4

Microsoft DOS 文本文件格式.

wdFormatDOSTextLineBreaks

5

Microsoft DOS 保留带换行符的文本文件格式.

wdFormatEncodedText

7

编码的文本格式.

wdFormatFilteredHTML

10

过滤HTML格式.

wdFormatFlatXML

19

Open XML file format saved as a single XML file.

wdFormatFlatXMLMacroEnabled

20

Open XML file format with macros enabled saved as a single XML file.

wdFormatFlatXMLTemplate

21

Open XML template format saved as a XML single file.

wdFormatFlatXMLTemplateMacroEnabled

22

Open XML template format with macros enabled saved as a single XML file.

wdFormatOpenDocumentText

23

OpenDocument Text format.

wdFormatHTML

8

标准 HTML format.

wdFormatRTF

6

富文本格式 (RTF).

wdFormatStrictOpenXMLDocument

24

Strict Open XML document format.

wdFormatTemplate

1

Word template format.

wdFormatText

2

Microsoft Windows text format.

wdFormatTextLineBreaks

3

Windows text format with line breaks preserved.

wdFormatUnicodeText

7

Unicode text format.

wdFormatWebArchive

9

Web archive format.

wdFormatXML

11

Extensible Markup Language (XML) format.

wdFormatDocument97

0

Microsoft Word 97 文档格式.

wdFormatDocumentDefault

16

Word 默认文档文件格式也就是DOCX格式.

wdFormatPDF

17

PDF 格式.

wdFormatTemplate97

1

Word 97 template format.

wdFormatXMLDocument

12

XML 文档格式.

wdFormatXMLDocumentMacroEnabled

13

XML document format with macros enabled.

wdFormatXMLTemplate

14

XML template format.

wdFormatXMLTemplateMacroEnabled

15

XML template format with macros enabled.

wdFormatXPS

18

XPS format.

下面是WdOpenFormat枚举值

名称


说明

wdOpenFormatAllWord

6

与 Word 早期版本向后兼容的 Microsoft Word 格式。

wdOpenFormatAuto

0

现有格式。

wdOpenFormatDocument

1

Word 格式。

wdOpenFormatEncodedText

5

编码文本格式。

wdOpenFormatRTF

3

RTF 格式。

wdOpenFormatTemplate

2

用作 Word 模板。

wdOpenFormatText

4

未编码的文本格式。

wdOpenFormatOpenDocumentText

18 (&H12)

OpenDocument 文本格式。

wdOpenFormatUnicodeText

5

Unicode 文本格式。

wdOpenFormatWebPages

7

HTML 格式。

wdOpenFormatXML

8

XML 格式。

wdOpenFormatAllWordTemplates

13

Word 模板格式。

wdOpenFormatDocument97

1

Microsoft Word 97 文档格式。

wdOpenFormatTemplate97

2

Word 97 模板格式。

wdOpenFormatXMLDocument

9

XML 文档格式。

wdOpenFormatXMLDocumentSerialized

14

打开 XML 文件格式保存为一个 XML 文件。

wdOpenFormatXMLDocumentMacroEnabled

10

启用了宏的 XML 文档格式。

wdOpenFormatXMLDocumentMacroEnabledSerialized

15

打开 XML 文件格式启用了宏保存为一个 XML 文件。

wdOpenFormatXMLTemplate

11

XML 模板格式。

wdOpenFormatXMLTemplateSerialized

16 (&H10)

单个文件保存为 xml 格式的开放 XML 模板格式。

wdOpenFormatXMLTemplateMacroEnabled

12

启用了宏的 XML 模板格式。

wdOpenFormatXMLTemplateMacroEnabledSerialized

17 (&H11)

打开 XML 模板启用了宏格式另存为单个的 XML 文件。