Python 实现HTML 转Word

发布时间 2023-12-29 16:33:15作者: E-iceblue

之前文章分享过如何使用Spire.Doc for Python库将Word文档转为HTML格式,反过来,该库也能实现HTML到Word文档的转换。通过代码进行转换,避免了手动复制粘贴费时间,并且可能会出现错误或格式混乱等问题。

Spire.Doc for Python库能转换一个HTML文件为 Word Docx 格式,也能直接将HTML字符串转为Word文档。具体实现方法查看下文。

 

首先通过以下pip命令安装该Python库:

pip install Spire.Doc

 

Python 将HTML文件转为Word

from spire.doc import *
from spire.doc.common import *
 
# 创建Document类的对象
document = Document()
 
# 加载一个HTML文件
document.LoadFromFile("input.html", FileFormat.Html, XHTMLValidationType.none)
 
# 将HTML文件保存为.docx格式
document.SaveToFile("Html文件转为Word.docx", FileFormat.Docx2016)
document.Close()

上述代码先加载了一个.html文件,然后通过调用 Document.SaveToFile() 方法就将该文件转换成了.docx 格式。三行Python代码轻松搞定HTML文件转Word。

效果图:

 

Python 将HTML字符串转为Word 

from spire.doc import *
from spire.doc.common import *
 
# 创建Document类的对象
document = Document()
 
# 在文档中添加一节
sec = document.AddSection()
 
# 在该节中添加一个段落
paragraph = sec.AddParagraph()
 
# 指定HTML字符串
htmlString = """
<html>
<head>
    <title>HTML转Word示例</title>
    <style>
        body {
            font-family: 微软雅黑, sans-serif;
        }
        h1 {
            color: #CC3333;
            font-size: 24px;
            margin-bottom: 20px;
        }
        p {
            color: #333333;
            font-size: 16px;
            margin-bottom: 10px;
        }
        ul {
            list-style-type: disc;
            margin-left: 20px;
            margin-bottom: 15px;
        }
        li {
            font-size: 14px;
            margin-bottom: 5px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 20px;
        }
        th, td {
            border: 1px solid #CCCCCC;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #F2F2F2;
            font-weight: bold;
        }
        td {
            color: #0000FF;
        }
    </style>
</head>
<body>
    <h1>标题示例</h1>
    <p>这是一个简单段落展示。</p>
    <p>无序列表:</p>
    <ul>
        <li>数学</li>
        <li>语文</li>
        <li>英语</li>
    </ul>
    <p>表格:</p>
    <table>
        <tr>
            <th>产品</th>
            <th>数量</th>
            <th>价格</th>
        </tr>
        <tr>
            <td>长裤</td>
            <td>30</td>
            <td>¥150</td>
        </tr>
        <tr>
            <td>毛衣</td>
            <td>2</td>
            <td>¥99</td>
        </tr>
    </table>
</body>
</html>
"""
 
# 将 HTML 字符串添加到段落中
paragraph.AppendHTML(htmlString)
 
# 保存结果文件
document.SaveToFile("Html字符串转Word.docx", FileFormat.Docx2016)
document.Close()

上述代码中,首先新建了一个Word文档并添加段落,然后通过 Paragraph.AppendHTML() 方法将HTML字符串插入到了Word文档的段落中,最后再保存文档即可将实现转换。生成文件如下图:

 

参考:Python Word 库各功能教程