Search code examples
pythoncsvdocx

How to write a CSV table to docx using python


I have a CSV file like the following one:

user,password,company
Administrator, 123456, test_company
test_user1, abcdf, test_company1
test_user2, 789, test_company2

This should be a table with user, password and company as headers.

How can I write this structure as a table in a docx file using python?


Solution

  • import docx 
    import csv
    
    doc = docx.Document()
    
    with open('csv.csv', newline='') as f:
        csv_reader = csv.reader(f) 
    
        csv_headers = next(csv_reader)
        csv_cols = len(csv_headers)
    
        table = doc.add_table(rows=2, cols=csv_cols)
        hdr_cells = table.rows[0].cells
    
        for i in range(csv_cols):
            hdr_cells[i].text = csv_headers[i]
    
        for row in csv_reader:
            row_cells = table.add_row().cells
            for i in range(csv_cols):
                row_cells[i].text = row[i]
    
    doc.add_page_break()
    doc.save("data.docx")
    

    Output:

    enter image description here