Daheh
Daheh

Reputation: 137

how to create docx files with python

I am trying to take my data and put it in tables in either microsoft words or libreoffice writer.

I need to be able to change the background of cells within the table and I need to be able to change the page property to 'landscape'.

I have been looking for a library with simple code ( I am a beginner in coding ) but I did not find one for what I need to do.

Have you heard of anything for me ? If there are example on how to use it that would make it easier for me to learn it.

Upvotes: 3

Views: 24178

Answers (2)

Shay
Shay

Reputation: 1499

The previous answer is a good one, but there is another way: create the document in Word then hack the xml in Python to insert the content you want. I have done this several times. In fact, my current invoicing program works this way.

Disadvantages: Conditional formatting and numbered lists will require some real xml knowledge.

Advantages: No limitations or intricate style definitions to manage. EVERYTHING is supported, because it's all done in Word.

Here's the workflow:

  1. create a *.docx document with marker text where you want your headings, table cells, etc.
  2. Use lxml to find those markers and copy their parent elements (along with their formatting).
  3. Use those found elements to create templates
  4. Insert your data into those templates, and assemble the whole thing like a jigsaw puzzle.
  5. Zip your xml into a new *.docx file.

I have a short sample project showing the procedure. Docx2Python does most of the work for you.

https://github.com/ShayHill/replace_docx_tables

Upvotes: 3

Morgoth
Morgoth

Reputation: 5176

Check out this project

And here is a great quick-start guide

It's pretty simple to use, i haven't tested this, but it should work:

from docx import Document

document = Document()
r = 2 # Number of rows you want
c = 2 # Number of collumns you want
table = document.add_table(rows=r, cols=c)
table.style = 'LightShading-Accent1' # set your style, look at the help documentation for more help
for y in range(r):
    for x in range(c):
        cell.text = 'text goes here'
document.save('demo.docx') # Save document

It don't think you can set the page orientation property with this library, but what you could do is create a blank word document that is in landscape yourself, store it in the working directory and make a copy of it every time you generate this document.

Upvotes: 4

Related Questions