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?
You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel. To export a Pandas DataFrame as an Excel file (extension: . xlsx, . xls), use the to_excel() method.
To insert multiple rows into the worksheet, call the insertRows method of the Cells collection. The InsertRows method takes two parameters: Row index, the index of the row from where the new rows will be inserted. Number of rows, total number of rows that need to be inserted.
Excel's text to column feature lets you easily split this data into separate columns. You simply select the column, click Data → Text to Columns, and delimit by a comma. And voila!
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:
pandas.ExcelWriter
pandas.DataFrame
pandas.DataFrame.to_excel
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:
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.
You can also do this with openpyxl library.
from openpyxl import Workbook
new_list = [["first", "second"], ["third", "fourth"]]
wb = Workbook() # creates a workbook object.
ws = wb.active # creates a worksheet object.
for row in new_list:
ws.append(row) # adds values to cells, each list is a new row.
wb.save('File_Name.xlsx') # save to excel file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With