Len
Len

Reputation: 43

How to add a list of list into excel using python xlsxwriter

I have a list l1=[['a','20,'30],['b','30','40']. I want l1 to be inserted in an Excel file with this format:

a   20   30
b   30   40 

Upvotes: 2

Views: 970

Answers (3)

Dishin H Goyani
Dishin H Goyani

Reputation: 7713

Using worksheet.write_column() with xlsxwriter

>>> import xlsxwriter
>>> a = [['a','20','30'],['b','30','40']]
>>> cl1 = [i[0] for i in a]                 # ['a', 'b']
>>> cl2 = [','.join(i[1:]) for i in a]      # ['20,30', '30,40']

>>> wbook = xlsxwriter.Workbook('Test.xlsx')
>>> wsheet = wbook.add_worksheet('Test')

>>> wsheet.write_column(0,0, cl1)
>>> wsheet.write_column(0,1, cl2)
>>> wbook.close()

Or

You can use pandas pandas.DataFrame.to_excel

>>> import pandas as pd
>>> df = pd.DataFrame.from_dict({'Column1':cl1,'Column2':cl2})
>>> df
  Column1 Column2
0       a   20,30
1       b   30,40

>>> df.to_excel('a_name.xlsx', header=True, index=False)

Upvotes: 1

Shadab Hussain
Shadab Hussain

Reputation: 814

Try this:

import openpyxl
l1 = [['a','20','30'],['b','30','40']]
wb = openpyxl.Workbook()
sheet = wb.active
le_ = len(l1)
for i in l1:
    c1 = sheet.cell(row=1,column=1)
    c1.value = i[0]
    c2 = sheet.cell(row=1,column=2)
    c2.value = ' '.join(each for each in i[1:])
wb.save("demo1.xlsx")

In sheet.cell(row=1,column=1) you can point to specific cell using row number and column number and can store data in what ever format you want

Upvotes: 0

René
René

Reputation: 4827

You can try:

import pandas as pd
l1 = [['a','20', '30'], ['b','30', '40']]
df = pd.DataFrame({'col1': [l[0] for l in l1],
                   'col2': [l[1:3] for l in l1]})
df.to_excel('output.xlsx')

Upvotes: 0

Related Questions