Formatted output in OpenOffice/Microsoft Word with Python

人走茶凉 提交于 2019-12-04 06:31:49

A little known, and slightly evil fact: If you create an HTML file, and stick a .doc extension on it, Word will open it as a Word document, and most users will be none the wiser.

Except maybe a very technical person will say, my this is a small Word file! :)

" The formatting is complex(bullet points, paragraphs, bold face, etc), "

Use RST.

It's trivial to produce, since it's plain text.

It's trivial to edit, since it's plain text with a few extra characters to provide structural information.

It formats nicely using a bunch of tools.

Use the Python Docx module for this - 100% Python, tables, images, document properties, headings, paragraphs, and more.

I know there is an odtwriter for docutils. You could generate your output as reStructuredText and feed it to odtwriter or look into what odtwriter is using on the backend to generate the ODT and use that.

(I'd probably go with generating rst output and then hacking odtwriter to output the stuff I want (and contribute the fixes back to the project), because that's probably a whole lot easier that trying to render your stuff to ODT directly.)

I've used xlwt to create Excel documents using python, but I haven't needed to write word files yet. I've found this package, OOoPy, but I haven't used it.

Also you might want to try outputting html files and having the users open them in Word.

You can use QTextDocument, QTextCursor and QTextDocumentWriter in PyQt4. A simple example to show how to write to an odt file:

>>>from pyqt4 import QtGui
# Create a document object
>>>doc = QtGui.QTextDocument()
# Create a cursor pointing to the beginning of the document
>>>cursor = QtGui.QTextCursor(doc)
# Insert some text
>>>cursor.insertText('Hello world')
# Create a writer to save the document
>>>writer = QtGui.QTextDocumentWriter()
>>>writer.supportedDocumentFormats()
[PyQt4.QtCore.QByteArray(b'HTML'), PyQt4.QtCore.QByteArray(b'ODF'), PyQt4.QtCore.QByteArray(b'plaintext')]
>>>odf_format = writer.supportedDocumentFormats()[1]
>>>writer.setFormat(odf_format)
>>>writer.setFileName('hello_world.odt')
>>>writer.write(doc) # Return True if successful
True

QTextCursor also can insert tables, frames, blocks, images. More information at: http://qt-project.org/doc/qt-4.8/qtextcursor.html

As a bonus, you also can print to a pdf file by using QPrinter.

I think OpenOffice has some Python bindings - you should be able to write OO macros in Python.

But I would use HTML instead - Word and OO.org are rather good at editing it and you can write it from Python easily (although Word saves a lot of mess which could complicate parsing it by your Python app).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!