I have an excel file of which I need to access individual data cells in a python code.?

I have an excel file of which I need to access individual data cells in a python code. There are too many cells to do it individually, so to access individual cells I need to do something like

for item in Excel_File:

print item[0]

how would you do this

Update:

are there modules I should download?

1 Answer

Relevance
  • 4 years ago
    Favorite Answer

    It depends. If you can save your spreadsheet in CSV format, there's a module in the standard library to read those:

    https://docs.python.org/2.7/library/csv.html

    That's the Python 2.7 documentation page. Use the drop-down at the top left for other versions. With this, you can read a CSV file one row at a time, getting a list of strings for each row of the spreadsheet. No attempt is made to convert fields to numbers, though. You'll have to do that yourself.

    If you're going to access the data out of order ("random access") then the fastest way to do that is to read the whole sheet into a Python list:

    import csv

    csv_data = []

    with open('MyData.csv', 'rb') as csv_file:

      for row in csv.reader(csv_file):

        csv_data.append(row)

    Now csv_data[row_index][col_index] has the cell value from row row_index (0 is the first row) and column col_index (0 is the first column).

    There are restrictions on what can be saved in CSV format. Only values are stored. Formatting and formulas are used to get cell values, and then are discarded. Only a single sheet can be saved. If you have anything interesting in your spreadsheet that you want to keep for other purposes, you need to keep that in regular XLS or XLSX format and then save a copy in CSV form for your Python code to process.

Still have questions? Get your answers by asking now.