user1681102
user1681102

Reputation: 193

Write data present in list to a column in excel sheet using xlxs writer module

I have two lists defined as:

Column1=[1,2,3,4]
Column2=[5,6,7,8]

I want to append the Column1 list to first column of an Excel sheet and the Column2 list to the second column of the Excel sheet. Excel sheet would look like:

enter image description here

My Code So Far:

from xlxswriter import*
workbook=Workbook('Ecl.xlxs')
Report_Sheet=workbook.add_worksheet()
for row_ind,row_value in enumerate(Column1):
    print row_ind,row_value
    Report_Sheet.write('A',Column1)#i want something similar to this

So each list should be appended to each column.

Upvotes: 4

Views: 18489

Answers (3)

jmcnamara
jmcnamara

Reputation: 41584

XlsxWriter has write_row() and write_column() methods to write lists of data in a single call. So you could write your column data like this:

from xlsxwriter import Workbook

Column1 = [1, 2, 3, 4]
Column2 = [5, 6, 7, 8]

workbook = Workbook('Ecl.xlsx')
Report_Sheet = workbook.add_worksheet()

# Write the column headers if required.
Report_Sheet.write(0, 0, 'Column1')
Report_Sheet.write(0, 1, 'Column2')

# Write the column data.
Report_Sheet.write_column(1, 0, Column1)
Report_Sheet.write_column(1, 1, Column2)

workbook.close()

Output:

enter image description here

Note: there is a typo in the file extension in your sample code. It is important in Excel to have the correct extension.

Upvotes: 4

Tiny.D
Tiny.D

Reputation: 6556

You could try with pandas like this:

import pandas as pd
df = pd.DataFrame.from_dict({'Column1':[1,2,3,4],'Column2':[5,6,7,8]})
df.to_excel('test.xlsx', header=True, index=False)

The test.xlsx will be like the one you need.

Update:

import pandas as pd
Column1 = [1,2,3,4]
Column2 = [5,6,7,8]
df = pd.DataFrame.from_dict({'Column1':Column1,'Column2':Column2})
df.to_excel('test.xlsx', header=True, index=False)

Upvotes: 5

Stephen Rauch
Stephen Rauch

Reputation: 49794

Using zip() and enumerate() can get the values you need to iterate over your data like:

Code:

Column1 = [1, 2, 3, 4]
Column2 = [5, 6, 7, 8]

from xlsxwriter import Workbook
workbook = Workbook('Ecl.xlsx')
Report_Sheet=workbook.add_worksheet()
Report_Sheet.write(0, 0, 'Column1')
Report_Sheet.write(0, 1, 'Column2')

for row_ind, row_value in enumerate(zip(Column1, Column2)):
    print row_ind, row_value
    for col_ind, col_value in enumerate(row_value):
        Report_Sheet.write(row_ind + 1, col_ind, col_value)

Upvotes: 2

Related Questions