我对Python非常陌生,我正在尝试将Excel表中的值复制到Word表中
这是我的代码
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"],
}
我尝试创建一个字典,其中每个键都是一个行单元格,它对应于 Excel 文件中的记录,但我陷入了这部分:
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
sda
是一个字典列表,而不是单个字典,你需要迭代它。
并且您不需要迭代
rows
中的单元格,因为您使用 rows.cells[0]
对其进行索引。
for rows, item in zip(Table.rows, sda):
Dictionary = {
rows.cells[0]: item["ORDER"],
rows.cells[1]: item["ITEM"],
rows.cells[2]: item["Q1"],
rows.cells[3]: item["Q2"],
rows.cells[4]: item["PRICE"],
rows.cells[5]: item["TVA"],
rows.cells[6]: item["TOTAL"],
}