【问题标题】:Convert HTML to Word document with python-docx?使用 python-docx 将 HTML 转换为 Word 文档?
【发布时间】:2016-01-02 10:36:36
【问题描述】:

我想从 HTML 字段生成 Word 文档(您可以将其写入文本并设置它的粗体、斜体、字体颜色大小、..)。我用这个 Python-docx 来生成 WOrd 文档。Everythink 没问题(添加图片、文本、..)唯一的问题是样式。问题是我在word文档中有内容但没有样式。

我尝试将内容保存为 HTML 文件,然后创建一个 python-docx 文件,如下所示:

html_f=open('f_html.html','w') 
html_f.write(u''+contenu) 
html_f.close() 


doc2=docx.Document('f_html.docx')

但我没有结果并且 Document() 没有找到该文件。 请帮忙

【问题讨论】:

    标签: python html python-2.7 python-docx


    【解决方案1】:

    Python-docx 只接受纯文本。您可以使用 Windows 的 pywin32 扩展来转换您的 html 文件。我发现了一个简单的例子:

    import win32com.client
    
    word = win32com.client.Dispatch('Word.Application')
    doc = word.Documents.Add('example.html')
    doc.SaveAs('example.doc', FileFormat=0)
    doc.Close()
    word.Quit() 
    

    【讨论】:

      【解决方案2】:

      或者:

      from htmldocx import HtmlToDocx
      
      new_parser = HtmlToDocx()
      new_parser.parse_html_file("html_filename", "docx_filename")
      #Files extensions not needed, but tolerated
      

      【讨论】:

        猜你喜欢
        • 2017-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-03
        • 1970-01-01
        • 1970-01-01
        • 2019-04-04
        相关资源
        最近更新 更多