如何在Python中将html转换为word docx?

问题描述 投票:0回答:3
import pypandoc
output = pypandoc.convert_file('file.html', 'docx', outputfile="file1.docx")
assert output == ""

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

谁能告诉我如何生成带有样式的新 docx 文件?

提前感谢您的回答。

python html ubuntu-16.04 doc
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'])

阅读 this 了解 extra_args。


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

0
投票

请使用此库生成 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
© www.soinside.com 2019 - 2024. All rights reserved.