0

I have code that writes stuff to cells in a table in a .docx file. The table already has pre-set formatting (e.g. size 16 Arial font, align right etc.). However, when python writes to the table, the formatting reverts to word's default (size 12 times new roman, alighn left).

Is there some function within the docx module to merge the formatting when writing to the table?

Example code:

from docx import Document

doc = Document('table.docx')
table = doc.tables[0]

table.cell(0, 0).text = str('blahblah')
doc.save('table.docx')

The long way would be to specify in the code what format to write it in but this can be really tedious having to write code for every single cell in a table that has different formatting. It's far easier to set the formatting in word than it is to write the code for it in python.

user155876
  • 361
  • 2
  • 14

1 Answers1

0

You can try using:

from docx.shared import Pt
font.name = 'Arial'
font.size = Pt(16)

More information can be found here

FELASNIPER
  • 327
  • 2
  • 9
  • This is exactly what I'm trying to avoid. If you have multiple cells all with different kinds of formatting, you would have to specify the format in the code for each cell with a unique formatting. This can be really tedious if you have 10 cells each with 10 different things (e.g. different font, font size, font colour, text alignment, bold, italicized, etc.) I was hoping there would be a more pythonic efficient way of simply merging to the document's format when writing to it. – user155876 Oct 10 '17 at 02:47
  • Have you looked into https://stackoverflow.com/questions/34779724/python-docx-replace-string-in-paragraph-while-keeping-style? and https://stackoverflow.com/questions/44874327/python-docx-how-to-apply-different-styles-to-different-cells-in-a-table – FELASNIPER Oct 10 '17 at 02:53