Writing to an Excel spreadsheet

Jey picture Jey · Nov 18, 2012 · Viewed 608.9k times · Source

I am new to Python. I need to write some data from my program to a spreadsheet. I've searched online and there seem to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest to write to a .csv file (never used CSV and don't really understand what it is).

The program is very simple. I have two lists (float) and three variables (strings). I don't know the lengths of the two lists and they probably won't be the same length.

I want the layout to be as in the picture below:

Layout sample

The pink column will have the values of the first list and the green column will have the values of the second list.

So what's the best way to do this?

P.S. I am running Windows 7 but I won't necessarily have Office installed on the computers running this program.

import xlwt

x=1
y=2
z=3

list1=[2.34,4.346,4.234]

book = xlwt.Workbook(encoding="utf-8")

sheet1 = book.add_sheet("Sheet 1")

sheet1.write(0, 0, "Display")
sheet1.write(1, 0, "Dominance")
sheet1.write(2, 0, "Test")

sheet1.write(0, 1, x)
sheet1.write(1, 1, y)
sheet1.write(2, 1, z)

sheet1.write(4, 0, "Stimulus Time")
sheet1.write(4, 1, "Reaction Time")

i=4

for n in list1:
    i = i+1
    sheet1.write(i, 0, n)



book.save("trial.xls")

I wrote this using all your suggestions. It gets the job done but it can be slightly improved.

How do I format the cells created in the for loop (list1 values) as scientific or number?

I do not want to truncate the values. The actual values used in the program would have around 10 digits after the decimal.

Answer

diliop picture diliop · Nov 18, 2012

Use DataFrame.to_excel from pandas. Pandas allows you to represent your data in functionally rich datastructures and will let you read in excel files as well.

You will first have to convert your data into a DataFrame and then save it into an excel file like so:

In [1]: from pandas import DataFrame
In [2]: l1 = [1,2,3,4]
In [3]: l2 = [1,2,3,4]
In [3]: df = DataFrame({'Stimulus Time': l1, 'Reaction Time': l2})
In [4]: df
Out[4]: 
   Reaction Time  Stimulus Time
0              1              1
1              2              2
2              3              3
3              4              4

In [5]: df.to_excel('test.xlsx', sheet_name='sheet1', index=False)

and the excel file that comes out looks like this:

enter image description here

Note that both lists need to be of equal length else pandas will complain. To solve this, replace all missing values with None.