0

I am trying to create a program that takes in excel data from a spreadsheet and puts that data into separate word documents. Below is my current code:

from docxtpl import DocxTemplate
import pandas as pd

excel_doc = pd.read_excel("facturen holding en xxx BESTE.xlsx", "Holding 2023")
word_doc = DocxTemplate("template.docx")

for index, row in excel_doc.iterrows():
    context = {"name": row['naam'], 
    "street": row['straat'],
    "postcode": row['postcode'], 
    "email": row['email'], 
    "date": row['datum'], 
    "invoice_number": row['factuurnummer'],  
    "periode": row['excl. btw'], 
    "BTW21%": row['btw'], 
    "factuurbedrag": row['incl. btw'],
    }
    invoice_num = context["invoice_number"]
    name = context["name"]

    word_doc.render(context)
    word_doc.save(f"{name}_{invoice_num}_periode.docx")

So I have put the placeholders already in template.docx with {{}} and the name inside. I have also added excel columns with the names like in the code name. But I get this error for some reason, I would appreciate it if anyone would tell me how to solve it?

Traceback (most recent call last): File "/Users/shayaansmac/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3803, in get_loc return self._engine.get_loc(casted_key) File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'naam'

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "/Users/shayaansmac/Desktop/Europell-Invoices/tempCodeRunnerFile.py", line 8, in context = {"name": row['naam'], File "/Users/shayaansmac/opt/anaconda3/lib/python3.8/site-packages/pandas/core/series.py", line 981, in getitem return self._get_value(key) File "/Users/shayaansmac/opt/anaconda3/lib/python3.8/site-packages/pandas/core/series.py", line 1089, in _get_value loc = self.index.get_loc(label) File "/Users/shayaansmac/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3805, in get_loc raise KeyError(key) from err KeyError: 'naam'

  • The error is suggesting that the `naam` column does not exist in the dataframe. Check for typos. For creating tables using pandas, see [here](https://github.com/elapouya/python-docx-template/issues/510#issuecomment-1698621930) – benkyou Aug 30 '23 at 08:08

0 Answers0