Jey Jey - 11 months ago 96
Python Question

Python - Write to Excel Spreadsheet

I am new to Python. I need to write some data from my program to a spreadsheet. I've searched online and there seems to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest to write to a csv file (never used csv & 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:

enter image description here

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? Thanks.

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


import xlwt



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")


for n in list1:
i = i+1
sheet1.write(i, 0, n)"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 Source
import xlwt

def output(filename, sheet, list1, list2, x, y, z):
    book = xlwt.Workbook()
    sh = book.add_sheet(sheet)

    variables = [x, y, z]
    x_desc = 'Display'
    y_desc = 'Dominance'
    z_desc = 'Test'
    desc = [x_desc, y_desc, z_desc]

    col1_name = 'Stimulus Time'
    col2_name = 'Reaction Time'

    #You may need to group the variables together
    #for n, (v_desc, v) in enumerate(zip(desc, variables)):
    for n, v_desc, v in enumerate(zip(desc, variables)):
        sh.write(n, 0, v_desc)
        sh.write(n, 1, v)


    sh.write(n, 0, col1_name)
    sh.write(n, 1, col2_name)

    for m, e1 in enumerate(list1, n+1):
        sh.write(m, 0, e1)

    for m, e2 in enumerate(list2, n+1):
        sh.write(m, 1, e2)

for more explanation: