python 从excel中获取数据写入word模板中

 1 # coding:<encoding name> : # coding: utf-8
 2 import xlrd2
 3 from docxtpl import DocxTemplate
 4 
 5 
 6 def main():
 7     data = xlrd2.open_workbook(r"data.xlsx")
 8     for x in range(0, 1):#这儿可以循环多张表
 9         print(x)
10         table = data.sheets()[x]
11         names = data.sheet_names()[x]  # 获取表名
12         nrows = table.nrows
13         print(names)
14 
15         for i in range(nrows):
16             name = table.row_values(i)[0]  # 姓名
17             idCard = table.row_values(i)[3]  # 身份证
18             smallMoney = table.row_values(i)[1]  # 金额小写
19             bigMoney = table.row_values(i)[2]  # 金额大写
20             month = table.row_values(i)[5]  # 月份
21             day = table.row_values(i)[6]  #
22             SMoney = str(smallMoney).replace(".0", "")#上面的数据打印出来会有.0,但是我们不需要,所以剔除。
23             SMonth = str(month).replace(".0", "")
24             Sday = str(day).replace(".0", "")
25             context = {
26                 "name": name,  # 姓名
27                 "idCard": idCard,  # 身份证号码
28                 "smallMoney": SMoney,  # 金额小写
29                 "bigMoney": bigMoney,  # 金额大写
30                 "month": SMonth,  #
31                 "day": Sday  #
32             }
33             word = DocxTemplate(r'template.docx')
34             print(context)
35             word.render(context)
36             word.save(f"{name}-{SMonth}-{Sday}-{names}.docx")
37             print("保存成功")
38 
39 
40 if __name__ == '__main__':
41     main()

 

posted @ 2023-02-02 09:35  星空沃土  阅读(304)  评论(0编辑  收藏  举报