Search code examples
pythondatetimevariablesraspberry-pipython-docx

Inserting a variable into a heading of a python-docx generated word doc


I am using python-docx for this task and am currently having difficulties in trying to insert a variable (i.e. month) into a heading of my python-docx generated word doc. Running the script successfully generates a word doc, but the heading is printed as current month instead of the desired 12(i.e. Dec). My python script is as shown below:

import datetime
import urllib
from docx import Document
from docx.shared import Inches

now = datetime.datetime.now()
currentmonth=now.month
print (currentmonth)

document = Document()

document.add_picture('placeholder.jpg', width=Inches(1.25))

document.add_heading('currentmonth', 0)

p = document.add_paragraph('A plain paragraph having some')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph(
    'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
    'first item in ordered list', style='ListNumber'
)

recordset = [
    {
        "id" : 1,
        "qty": 2,
        "desc": "New item"
    },
    {
        "id" : 2,
        "qty": 2,
        "desc": "New item"
    },
    {
        "id" : 3,
        "qty": 2,
        "desc": "New item"
    },

]

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for item in recordset:
    row_cells = table.add_row().cells
    row_cells[0].text = str(item["qty"])
    row_cells[1].text = str(item["id"])
    row_cells[2].text = item["desc"]

document.add_page_break()

document.save('demo.docx')

The difficulty arise at **document.add_heading('currentmonth', 0)**. When I remove the quotation marks to get document.add_heading(currentmont', 0), terminal shows me an error when I run the script. The error is shown below:

pi@raspberrypi:~/user $ python demo_script_v01.py
12
Traceback (most recent call last):
  File "demo_script_v01.py", line 14, in <module>
    document.add_heading(currentmonth, 0)
  File "/usr/local/lib/python2.7/dist-packages/python_docx-0.8.6-py2.7.egg/docx/document.py", line 43, in add_heading
    return self.add_paragraph(text, style)
  File "/usr/local/lib/python2.7/dist-packages/python_docx-0.8.6-py2.7.egg/docx/document.py", line 63, in add_paragraph
    return self._body.add_paragraph(text, style)
  File "/usr/local/lib/python2.7/dist-packages/python_docx-0.8.6-py2.7.egg/docx/blkcntnr.py", line 36, in add_paragraph
    paragraph.add_run(text)
  File "/usr/local/lib/python2.7/dist-packages/python_docx-0.8.6-py2.7.egg/docx/text/paragraph.py", line 37, in add_run
    run.text = text
  File "/usr/local/lib/python2.7/dist-packages/python_docx-0.8.6-py2.7.egg/docx/text/run.py", line 163, in text
    self._r.text = text
  File "/usr/local/lib/python2.7/dist-packages/python_docx-0.8.6-py2.7.egg/docx/oxml/text/run.py", line 104, in text
    _RunContentAppender.append_to_run_from_text(self, text)
  File "/usr/local/lib/python2.7/dist-packages/python_docx-0.8.6-py2.7.egg/docx/oxml/text/run.py", line 134, in append_to_run_from_text
    appender.add_text(text)
  File "/usr/local/lib/python2.7/dist-packages/python_docx-0.8.6-py2.7.egg/docx/oxml/text/run.py", line 141, in add_text
    for char in text:
TypeError: 'int' object is not iterable

Given this issue, does any one have a solution on how I can insert the current month as a variable into the heading, so that it appears in my word doc after running this script?


Solution

  • The first argument of the add_heading method is a string (see the documentation here). To convert currentmonth (which is an integer) into a string, simply use str(currentmonth) as follows:

    document.add_heading(str(currentmonth), 0)