16

I want to get particular cell values from excelsheet in my python script. I came across xlrd, xlwt, xlutils modules for reading/writing to/from excelsheet.

I created myfile.xls with hi, hello, how in first column's 3 cells.

sample code :-

import xlrd

workbook = xlrd.open_workbook('myfile.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = -1
while curr_row < num_rows:
        curr_row += 1
        row = worksheet.row(curr_row)
        print row

output :-

[text:u'hi']
[text:u'hello']
[text:u'how']

I want to read specific cell values from excelsheet, can someone suggest me if there is a way to do that?

npatel
  • 1,081
  • 2
  • 13
  • 21

5 Answers5

23

To access the value for a specific cell you would use:

value = worksheet.cell(row, column)

StvnW
  • 1,772
  • 13
  • 19
  • 1
    I tried it `value = worksheet.cell(1, 1)`, but it is giving error `self._cell_types[rowx][colx], IndexError: array index out of range`. I am using python2.5 and all required modules are installed. – npatel Oct 20 '13 at 17:35
  • 3
    The first column or row is `0`, not `1`. – StvnW Oct 20 '13 at 17:39
7

This code is to select certain cells from Excel using Python:

import openpyxl

wb = openpyxl.load_workbook(r'c:*specific destination of file*.xlsx')
sheet = wb.active
x1 = sheet['B3'].value
x2 = sheet['B4'].value
y1 = sheet['C3'].value
y2 = sheet['C4'].value
print(x1,x2,y1,y2)
Cronje Fourie
  • 71
  • 1
  • 1
5

To access the value for a specific cell:

cell_value = worksheet.cell(row_number, column_number).value
Bharath_Raja
  • 622
  • 8
  • 16
0

The code below will help you in solving the problem:

worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = 0
while curr_row < num_rows:
        curr_row += 1
        row = worksheet.row(curr_row)
        print row[0].value
roelofs
  • 2,132
  • 20
  • 25
jebran
  • 31
  • 3
0

Code snippet for reading xlsx file in python using xlrd

import xlrd

def readdata():
    workbook = xlrd.open_workbook("src.xlsx", "rb")
    sheets = workbook.sheet_names()
    for sheet_name in sheets:
        sh = workbook.sheet_by_name(sheet_name)
        for rownum in range(1, sh.nrows): #skipping header of the xlsx
           print(sh.cell(rownum, 2)) # e.g Printing all rows value of 3rd column

readdata()

if any error 'No Module found xlrd'. Install xlrd using below command in terminal

pip install xlrd
Bharathiraja
  • 714
  • 1
  • 12
  • 20
  • I get an error telling me that `.xlsx` is not supported. Apparently `xlrd` has removed support for anything other than `.xls` files, see https://stackoverflow.com/questions/65254535/xlrd-biffh-xlrderror-excel-xlsx-file-not-supported – Taylrl Jun 29 '22 at 11:15