Search code examples
pythonpython-3.xcsvxlsx

How to convert code to write data in xlsx instead of csv using python without pandas?


I have written a python code to store data in csv format but now need to store in .xlsx file. how to convert the below code and write the output in .xlsx file.

  details_file = self.get_local_storage_path() + '/Myfile.xlsx'
  csv_columns = (
        'id', 'name', 'place', 'salary', 'email',
          )

   with open(details_file, 'w') as csvfile:
            writer = csv.DictWriter(
                csvfile, fieldnames=csv_columns, extrasaction='ignore')
            writer.writeheader()
            for data in details:
                writer.writerow(data)
                
                
                
                

#I tried as below but getting error as TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'

with open(details_file, 'w') as csvfile:           
            print("inside open")
            workbook = xlsxwriter.Workbook(csvfile)
            worksheet = workbook.add_worksheet()
            print("before for loop")
            for data in details:
                worksheet.write(data)
            workbook.close()

Solution

  • I would use pandas for this:

    import pandas as pd
    
    # create the dataframe
    df = pd.DataFrame(dict(zip(csv_columns, details)))
    
    # save to csv:
    df.to_csv(path, index=False)
    
    #save to xlsx:
    df.to_excel(path, index=False)
    

    You might need to install openpyxl for the last line to work.

    But if you really need to use xlsxwriter for this, here's how I would do it based on their tutorial:

    import xlsxwriter
    
    csv_columns = (
        'id', 'name', 'place', 'salary', 'email',
    )
    details = [
        [1, 'A', 'B', 2, 'c@d.com'],
        [3, 'C', 'D', 4, 'e@f.com'],
    ]
    
    workbook = xlsxwriter.Workbook(path)
    worksheet = workbook.add_worksheet()
    
    for col, name in enumerate(csv_columns):
        worksheet.write(0, col, name)
    
    for row, det in enumerate(details, 1):
        for col, value in enumerate(det):
            worksheet.write(row, col, value)
    
    workbook.close()