Home » excel » python – How do you write several arrays into an excel file?

python – How do you write several arrays into an excel file?

Posted by: admin May 14, 2020 Leave a comment

Questions:

If I had several arrays I want to write into an excel file using Python, what would be the best way to go about it? I’ve tried several ways and cant figure it out…. this is an example of one way I was trying… Im quite new to this

import xlwt
from tempfile import TemporaryFile
book = xlwt.Workbook()
sheet1 = book.add_sheet('sheet1')


a=[1,2,3,4,5]
b=[6,7,8,9,10]
c=[2,3,4,5,6]

data = [a,b,c]

for i,e in enumerate(data):
    sheet1.write(i,1,e)

name = "this.xls"
book.save(name)
book.save(TemporaryFile())
How to&Answers:

As per Steven Rumbalski suggestion,

import xlwt
from tempfile import TemporaryFile
book = xlwt.Workbook()
sheet1 = book.add_sheet('sheet1')


a=[1,2,3,4,5]
b=[6,7,8,9,10]
c=[2,3,4,5,6]

data = [a,b,c]

for row, array in enumerate(data):
    for col, value in enumerate(array):
        sheet1.write(row, col, value):

name = "this.xls"
book.save(name)
book.save(TemporaryFile())

Answer:

Another option at your disposal is to write the arrays as a delimited text file. Excel can read those easily (just open them like they’re an Excel sheet and you will get the import dialog).

Here’s the code for doing that –

path='foo.txt'

a=[1,2,3,4,5]
b=[6,7,8,9,10]
c=[2,3,4,5,6]

with open(path,'w') as table:
    for row in zip(a,b,c):
        for cell in row:
            table.write(str(cell) + '\t')
        table.write('\n')

In this case the arrays are written vertically, and cells are delimited by tabs (Excel handles the redundant tab without problems).