我有一个excel工作表和一个模板,希望使用python生成多个模板,但出现了错误

2024-06-16 09:50:54 发布

您现在位置:Python中文网/ 问答频道 /正文

import random
import time
import xlsx
import pandas as pd
from docxtpl import DocxTemplate

# Source Excel - column names that must match the *** that are {{***}} inside "template.docx"
csvfn = "SampleTemplate.xlsx"

def mkw(n,fname):
    tpl = DocxTemplate("Document1.docx") # In same directory
    df = pd.read_excel (r'SampleTemplate.xlsx')
    # df = pd.read_xlsx(csvfn)
    df_to_doct = df.to_dict() # dataframe -> dict for the template render
    x = df.to_dict(orient='records')
    context = x
    tpl.render(context[n])
    tpl.save("%s.docx" %fname)

    # Wait a random time - increase to (60,180) for real production run.
    wait = time.sleep(random.randint(1,2))

#-------------------Main---------------------#

df2 = len(pd.read_excel(csvfn))

print ("There will be ", df2, "files")

for i in range(0,df2):
    df = pd.read_excel(csvfn)
    columnsData = df.loc[ : , 'title' ]
    fname = columnsData[i]
    print("Making file: ",f"{fname}," ,"..Please Wait...")
    mkw(i,fname)

print("Done! - Now check your files")

以及获取错误,以便任何人都可以帮助我解决问题,以便我可以生成多个文件 我还通过pip install xlrd 安装了xlrd。谁知道正确的解决方案?请帮助我解决此问题,并告诉我如何修改代码以生成模板docx文件或excel生成的文件谢谢

c:\Users\Mohd. Aquib\Desktop\New folder\new sample\pdoc-xlsx.py in 
      7 import random
      8 import time
----> 9 import xlsx
     10 import pandas as pd
     11 from docxtpl import DocxTemplate

ModuleNotFoundError: No module named 'xlsx' ```

Tags: toimportdfreadtimerandomxlsxexcel