ODFPY - OpenDocument Python API
ODFPY is a Python library and collection of utility programs designed to manipulate OpenDocument Format (ODF) files (e.g., .odt, .ods, .odp). It provides a structured API that adheres rigorously to ODF specifications, focusing on preventing the creation of invalid documents by incorporating grammar checks. The current version is 1.4.1. While new releases are infrequent, it is officially considered actively maintained by its community.
Warnings
- gotcha The official documentation for ODFPy is often described as highly technical and lacking in conceptual examples, making it challenging for newcomers. Users frequently resort to studying the provided examples and source code to understand usage patterns.
- gotcha While officially considered 'active maintenance', ODFPy has an infrequent release cycle (latest release 1.4.1 in January 2020). For projects requiring more frequent updates or active development, alternatives like `odfdo` (also listed by The Document Foundation) might be considered.
- gotcha ODFPy rigorously enforces OpenDocument Specification 1.2 through grammar checks. This means attempts to add invalid elements, unknown attributes, or text to unsupported elements will raise exceptions, preventing the creation of malformed documents. This strictness can be a 'gotcha' for users expecting more lenient XML handling.
- gotcha Many examples and the library's design are more geared towards *creating* new ODF documents rather than *reading* and parsing content from existing ones. Finding clear, simple examples for extracting data from existing .odt or .ods files can be challenging.
- deprecated Older documentation and examples might point to the `joinup.ec.europa.eu` domain. This source is obsolete and should not be used for current information or downloads.
Install
-
pip install odfpy
Imports
- OpenDocumentText
from odf.opendocument import OpenDocumentText
- load
from odf.opendocument import load
- P
from odf.text import P
- Style
from odf.style import Style
- teletype
from odf import teletype
Quickstart
from odf.opendocument import OpenDocumentText
from odf.text import P
import os
# Create a new ODT document
textdoc = OpenDocumentText()
# Create a paragraph and add some text
p = P(text="Hello, ODFPy World!")
# Add the paragraph to the document's text body
textdoc.text.addElement(p)
# Save the document to 'helloworld.odt'
# The 'prettyprint=True' argument formats the XML for readability.
try:
output_filename = os.path.join(os.getcwd(), "helloworld.odt")
textdoc.save(output_filename, prettyprint=True)
print(f"Document '{output_filename}' created successfully.")
except Exception as e:
print(f"Error saving document: {e}")