[Tutor] Getting info out of an Excel spreadsheet

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 11 Aug 2002 19:55:36 -0700 (PDT)


On Fri, 9 Aug 2002, Jose Alberto Abreu wrote:

> Is there any not-too-difficult way to pull out two columns out of an
> Excel file, convert them into lists and play with them?

If you can convert your Excel file into a "tab-delimited" flat text file,
that might be an easy way of extracting the columns out.  I'm pretty sure
Excel can do this; check in the "Save as" command in the File menu.

Once you have your data as a flat text file, you can use the file and
string tools that Python provides, including the string.split() function.

Let's say that our flat text file looked like this:

###
1	2
3	4
5	6
7	8
###

and let's say that we wanted to get the sum of both columns --- we can go
about it like this:

###
my_data_file = open('flat_data.txt')
sum1, sum2 = 0, 0
for line in my_data_file:
    column1, column2 = line.split()
    sum1 = sum1 + int(column1)
    sum2 = sum2 + int(column2)
print "sum1:", sum1
print "sum2:", sum2
###