Maysara Anani
Maysara Anani

Reputation: 1

copy data table from csv file to word document in table using python and jinja2

Anyone can help me for my code, I am using existing Word Template to extract from csv file to write in table inside template word, and using python libraries such as: docxtpl, pandas, csv

user.dst    device.ip   count(user.dst)
user1   192.168.102.128 475
user2   192.168.102.128 113
user3   192.168.102.128 43
user4   192.168.102.128 23
user5   192.168.102.128 3
user6   192.168.102.128 2

i write the code below but not sure is correct

from docxtpl import DocxTemplate
    import docx as doc
    import pandas as pd
    import csv
    
    doc = DocxTemplate("daily report.docx")
    csvfn = "csv_file.csv"
    
    ############################## Read Csv File Data #####################
    
    with open (csvfn,"r") as csvf:
        op = csvf.readlines()
        Dbusertbl = []   
        user_source=[]
        session_count=[]
    for i in op[0:]:
           user_source = i.split(",")[0]
           Session_count = i.split(",")[1]
           Dbusertbl.append({"user_name":user_source,"session_count":Session_count})
           print(Dbusertbl)
    
    ################################# Context ############################################
    context = {
      
        "DbTblRows":Dbusertbl
        
    
    }
    
    doc.render(context)
    
    
    
    doc.save("newword.docx")

Also, Ii added jinja2 syntax to the word. please find the picture in this link.

word word using jinja2

Upvotes: 0

Views: 866

Answers (1)

p_sutherland
p_sutherland

Reputation: 491

Load your data into a nested dictionary with this structure:

username_dict = {'user1': {"ip":"192.168.102.128", "user_dst_count":"475"},
            'user2': {"ip":"192.168.102.128", "user_dst_cnt":"113"},
            'user3': {"ip":"192.168.102.128", "user_dst_cnt":"43"},
            'user4': {"ip":"192.168.102.128", "user_dst_cnt":"23"},
            'user5': {"ip":"192.168.102.128", "user_dst_cnt":"3"},
            'user6': {"ip":"192.168.102.128", "user_dst_cnt":"2"}}

One way to do this using pandas would be:

df = pd.read_csv(path_to_csv_input_file)
username_dict = {}
for index, row in df.iterrows():
    username_dict[row['username']]={"ip":row['ip'], "user_dst_cnt":row["user_dst_cnt"]}

Next, you need to tweak your template file to look like this: enter image description here

Finally, set the context to context = {'username_dict':username_dict} and render for your desired output: enter image description here

Upvotes: 0

Related Questions