How to write a list of list into excel using python?

65,923

Solution 1

Here is one way to do it using XlsxWriter:

import xlsxwriter

new_list = [['first', 'second'], ['third', 'four'], [1, 2, 3, 4, 5, 6]]

with xlsxwriter.Workbook('test.xlsx') as workbook:
    worksheet = workbook.add_worksheet()

    for row_num, data in enumerate(new_list):
        worksheet.write_row(row_num, 0, data)

Output:

enter image description here

Solution 2

You can use the pandas library.

import pandas as pd

new_list = [["first", "second"], ["third", "four"], ["five", "six"]]
df = pd.DataFrame(new_list)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='welcome', index=False)
writer.save()

Related documentation:

Solution 3

I think you should use pandas library to write and read data in this library the function pandas.DataFrame.to_excel(..) will make you able to directly write to excel files for all this you may need to define pandas.DataFrame for this work here is a tutorial on pandas-dataframe by dataCamp.

Share:
65,923
pythoncoder
Author by

pythoncoder

Updated on July 29, 2020

Comments

  • pythoncoder
    pythoncoder almost 4 years

    How to write a list of list into excel using python 3?

    new_list = [["first", "second"], ["third", "fourth"]]
    with open("file_name.csv", 'w') as f:
        fc = csv.writer(f, lineterminator='\n')
    fc.writerows(new_list)
    

    I can write this list into csv file but How canI want to write in excel file?

  • Sachin
    Sachin almost 2 years
    AttributeError: 'list' object has no attribute 'to_excel'