如何使用 Python 创建 Word 文档? [英] How can I create a Word document using Python?
问题描述
我想使用 Python 创建 Word 文档,但是,我想尽可能多地重复使用现有的文档创建代码.我目前正在使用 XSLT 生成一个 HTML 文件,我以编程方式转换为 PDF 文件.但是,我的客户现在要求以 Word (.doc) 格式提供相同的文档.
I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I programatically convert to a PDF file. However, my client is now requesting that the same document be made available in Word (.doc) format.
到目前为止,我还没有找到任何解决此问题的方法.有人知道可以帮助解决此问题的开源库(或 *gulp* 专有解决方案)吗?
So far, I haven't had much luck finding any solutions to this problem. Is anyone aware of an open source library (or *gulp* a proprietary solution) that may help resolve this issue?
注意:所有可能的解决方案都必须在 Linux 上运行.我相信这会消除 pywin32.
NOTE: All possible solutions must run on Linux. I believe this eliminates pywin32.
推荐答案
使用 Python 创建 Word 文档的几种方法:
A couple ways you can create Word documents using Python:
- 使用 COM 自动化通过 MS Word 对象模型(使用
pywin32
)创建文档.http://python.net/crew/pirx/spam7/ - 使用 Python 自动化 OpenOffice:http://wiki.services.openoffice.org/wiki/Python
- 如果 rtf 格式正常,请使用 PyRTF 库:http://pyrtf.sourceforge.net/
- Use COM automation to create a document using the MS Word object model (using
pywin32
). http://python.net/crew/pirx/spam7/ - Automate OpenOffice using Python: http://wiki.services.openoffice.org/wiki/Python
- If rtf format is OK, use the PyRTF library: http://pyrtf.sourceforge.net/
既然 COM 是不可能的,我建议如下(灵感来自@kcrumley 的回答):
Since COM is out of the question, I suggest the following (inspired by @kcrumley's answer):
使用UNO库从python自动化Open Office,在OOWriter中打开HTML文件,然后另存为.doc.
Using the UNO library to automate Open Office from python, open the HTML file in OOWriter, then save as .doc.
编辑 2:
现在有一个看起来不错的纯 Python python-docx 项目(我没用过).
There is now a pure Python python-docx project that looks nice (I have not used it).
这篇关于如何使用 Python 创建 Word 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!