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:
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.
EDIT
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.
The easiest way to import the exact numbers is to add a decimal after the numbers in your
l1
andl2
. Python interprets this decimal point as instructions from you to include the exact number. If you need to restrict it to some decimal place, you should be able to create a print command that limits the output, something simple like:Would restrict it to the tenth decimal place, assuming your data has two integers left of the decimal.
OpenPyxl
is quite a nice library, built to read/write Excel 2010 xlsx/xlsm files:https://openpyxl.readthedocs.io/en/stable
The other answer, referring to it is using the deperciated function (
get_sheet_by_name
). This is how to do it without it:CSV stands for comma separated values. CSV is like a text file and can be created simply by adding the .CSV extension
for example write this code:
you can open this file with excel.
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:
and the excel file that comes out looks like this:
Note that both lists need to be of equal length else pandas will complain. To solve this, replace all missing values with
None
.for more explanation: https://github.com/python-excel