我使用python模块docxtpl (https://pypi.org/project/docxtpl/)在用jinja2编写的文档模板中打印数据。到目前为止效果很好,但我需要在docx中呈现一些简单的HTML,如下所示:
<h2>Some title</h2>
<h4>Lorem ipsum <strong>dolor sit amet</strong>, consectetur adipisicing elit. Possimus, aliquam,
minima fugiat placeat provident optio nam reiciendis eius beatae quibusdam!</h4>
<p style="font-size: 18px;">The text is derived from Cicero's De Finibus Bonorum et Malorum (On the Ends of Goods
and Evils, or alternatively [About] The Purposes of Good and Evil). The original passage began: Neque porro
quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit (Translation: "Neither is
there <del>anyone</del> who loves grief itself since it is grief and thus wants to obtain it").</p>
<table class="table">
<tbody>
<tr>
<td>Test</td>
<td>Test1</td>
<td>Test2</td>
<td>Test3</td>
</tr>
<tr>
<td>Lorem</td>
<td>Lorem1</td>
<td>Lorem2</td>
<td>Lorem3</td>
</tr>
<tr>
<td>Ipsum</td>
<td>Ipsum1</td>
<td>Ipsum2</td>
<td>Ipsum3</td>
</tr>
</tbody>
</table>不幸的是,我不能使用docxtpl中的RichText()来呈现表格和其他html内容。
我试着想出一些解决方案,但我想知道是否还有更好的方法,例如,将由html usign htmldocx (https://pypi.org/project/htmldocx/)生成的文档与使用docxtpl生成的文档合并,或者使用python-docx模块从一个文档中获取内容并将其插入到另一个文档中。
在最坏的情况下,我也愿意切换到JavaScript/BASH。
发布于 2021-04-01 17:17:17
from htmldocx import HtmlToDocx
new_parser = HtmlToDocx()
new_parser.parse_html_file("html_filename", "docx_filename")
#Files extensions not needed, but tolerated这对于在docx中转换html应该是个不错的办法。
我不确定我是否理解你的合并问题。最好的方法当然是用html代替你的docx模板。然后,一旦您将所需的所有内容都转储到一个html文件中,就可以将其转换为docx。
如果你想合并/插入docx,你可以看看这里:How do I append new data to existing doc/docx file using Python
https://stackoverflow.com/questions/66901713
复制相似问题