JeffC
JeffC

Reputation: 133

Cant apply table style in word doc using docx python

I cannot apply a custom table style to a WORD doc using python 3.4. I followed a great method by @scanny: I created a blank WORD doc, created a custom table style and saved it as "OR". I created a new table and applied the custom table style to it. I then deleted the table and saved the doc as "template.docx. I then applied the style as follows:

document = Document("C:/pytest/template.docx")
table = document.add_table(rows=1, cols=3)
table.style = "OR"
hdr_cells = table.rows[0].cells
hdr_cells[0].paragraphs[0].add_run('Date Filmed:').bold = True
hdr_cells[2].paragraphs[0].add_run('Barcode Number:').bold = True
row_cells = table.add_row().cells
row_cells[0].text = date
row_cells[2].text = bcode

When I run the program, it gets an error: File "C:\Python34\lib\site-packages\python_docx-0.8.5-py3.4.egg\docx\styles\styles.py", line 57, in getitem raise KeyError("no style with name '%s'" % key) KeyError: "no style with name 'Title'"

It is not specifying a line in the code, but a file named "styles.py". Do I have the syntax wrong?

thanks, Jeff

Upvotes: 5

Views: 10240

Answers (3)

captnolimar
captnolimar

Reputation: 105

You need to specify a style object when you are setting table.style = "OR".

So, what you would do to make this works is table.style = document.styles['OR']

The most concise way to do this would be to specify the style when you are creating the table such as: table = document.add_table(rows=1, cols=3, style=document.styles['OR'])

Upvotes: 0

JGC
JGC

Reputation: 6373

Your steps were described as:

I created a blank WORD doc, created a custom table style and saved it as "OR". I created a new table and applied the custom table style to it. I then deleted the table and saved the doc as "template.docx.

Can I suggest trying an additional step:

  1. Create blank word doc
  2. Create custom table style, saved with a specific name.
  3. Create a new table and apply the custom table style to it.
  4. !! SAVE the document WITH the new table !!
  5. Delete the table.
  6. Save the doc as template.docx.

If you don't save the document with the new table that uses the style then the style won't be written to the file.

I have had success using custom table styles using python-docx and this step caught me out.

Upvotes: 1

jesse
jesse

Reputation: 11

Old thread, still a problem. The problem lies in "document". Your template.docx doesn't use the "OR" style and so it's not saved there. Instead, use a generic, empty document i.e. generic_document=Document() and then reference that for your styles table.style = generic_document.styles['OR'].

Upvotes: 1

Related Questions