如何在Python中将HTML转换为Word Docx?

20
import pypandoc
output = pypandoc.convert_file('file.html', 'docx', outputfile="file1.docx")
assert output == ""

它正在生成新的docx文件,但忽略了样式。

有人可以告诉我如何生成带有样式的新docx文件吗?

提前感谢您的回答。


1
请查看此链接:https://dev59.com/PXNA5IYBdhLWcg3wQ7Yw 和 http://python-docx.readthedocs.io/en/latest/user/styles-using.html - Farmer
这个回答解决了你的问题吗?Python中的HTML转DOC转换器? - Rene
3个回答

14

在Windows中,最简单的方法是使用pywin32插件来使用MS Word。这里有一个很好的答案,包括示例代码:链接在这里

使用pypandoc:

output = pypandoc.convert(source='/path/to/file.html', format='html', to='docx', outputfile='/path/to/output.docx', extra_args=['-RTS'])

阅读这个链接以获取额外的参数。


它可以工作,但是pypandoc不支持CSS样式。 - Chabanenko Sergey
@СергейЧабаненко 您可以使用 extra_args='--css=custom_file.css' 来包含 CSS 文件。您可以使用静态文件或使用模板生成临时文件来完成此操作。 - Emin Mastizada
@EminMastizada 看起来 --css 参数在转换为 HTML 时使用,但在从 HTML 转换时被忽略了。或者我有什么遗漏吗? - Matthew Strawbridge

11
你也可以在Python 3.x中使用 htmldocx
from htmldocx import HtmlToDocx

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

1
请使用这个库来生成html2docx。
from django.shortcuts import render
from django.http import HttpResponse
from io import BytesIO
from html2docx import html2docx

def generate_docx(request):
    context = {
    'data': 'Hello, this is your data!',
   }
   html_content_bytes = render(request, 'your_template.html', 
   context).content
   html_content_str = html_content_bytes.decode('utf-8') 
  
   output = BytesIO()
   byte_data = html2docx(html_content_str, output)


   response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
   response['Content-Disposition'] = 'attachment; filename=output.docx'
   response.write(byte_data.getvalue())

   return response

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接