I'm very new to python and i'm trying to copy values from an excel table to a word table
here's my code
import pandas as pd
from docx import Document
from docxtpl import DocxTemplate
from pathlib import Path
base_dir = Path(__file__).parent
word_template_path = base_dir / "WordTemplate.docx"
excel_path = base_dir / "ExcelSource.xlsx"
output_dir = base_dir / "OUTPUT"
# Create output folder for the word document
output_dir.mkdir(exist_ok=True)
# convert Excel Sheet Into Pandas Dataframe
df = pd.read_excel(excel_path, sheet_name="Feuil2")
# dataframe to dictionary
sda = df.to_dict("records")
doc = Document("WordTemplate.docx")
#get the first table in the document
Table = doc.tables[0]
for rows in Table.rows:
for cells in rows.cells:
Dictionary = {
rows.cells[0]: sda["ORDER"],
rows.cells[1]: sda["ITEM"],
rows.cells[2]: sda["Q1"],
rows.cells[3]: sda["Q2"],
rows.cells[4]: sda["PRICE"],
rows.cells[5]: sda["TVA"],
rows.cells[6]: sda["TOTAL"],
}
i tried to create a dictionary where each key is a row cell and it corresponds to record from the excel file but i'm stuck in this part where it says :
Traceback (most recent call last):
File "C:\Users\wewsos\Desktop\Folders\New folder\New folder (9)\PythonTest\fufu\ha.py", line 26, in <module>
rows.cells[0]: sda["ORDER"],
~~~^^^^^^^^^
TypeError: list indices must be integers or slices, not str
sdais a list of dictionaries, not a single dictionary, you need to iterate over it.And you don't need to iterate over the cells in
rows, since you're indexing it withrows.cells[0].