Python USES the third party library xlrd to read the Excel sample

  • 2020-05-05 11:26:10
  • OfStack

This article shows you how to use xlrd to read the contents of the Excel table. xlrd is a third-party library, so we need to install xlrd before using it. In addition, we usually use xlwt to write Excel, so in the next article we will introduce how to write Excel using xlwt. xlrd download: xlrd 0.8.0

installs xlrd

To install xlrd, you just need to run setup, or you can unzip it into your project or use

xlrd API

Get Excel, which is called work book
here


open_workbook(file_name)

There are two ways to get the specified Sheet,


sheet = xls.sheet_by_index(sheet_no) 
sheet = xls.sheet_by_name(sheet_name)

Gets the values (array)
for the entire row and column

sheet.row_values(i)  
sheet.col_values(i)

Gets the total number of rows and total number of columns


nrows = sheet.nrows  
ncols = sheet.ncols

USES xlrd

Using xlrd here is a simple example:


# -*- coding: utf-8 -*- 
''''' 
Created on 2012-12-14 
 
@author:  walfred
@module: XLRDPkg.read 
@description:
'''   
import os 
import types 
import xlrd as ExcelRead 
 
def readXLS(file_name): 
    if os.path.isfile(file_name): 
        try: 
            xls = ExcelRead.open_workbook(file_name) 
            sheet = xls.sheet_by_index(0) 
        except Exception, e: 
            print "open %s error, error is %s" %(file_name, e) 
            return 
 
    rows_cnt = sheet.nrows 
    for row in range(1, rows_cnt): 
        name = sheet.row_values(row)[0].encode("utf-8").strip() 
        sex = sheet.row_values(row)[1].encode("utf-8").strip() 
        age = sheet.row_values(row)[2] 
        if type(age) is types.FloatType:# Read the type  
            no = str(int(age)) 
        else: 
            age = no.encode("utf-8").strip() 
 
        country = sheet.row_values(row)[3].encode("utf-8").strip() 
        print "Name: %s, Sex: %s, Age: %s, Country: %s" %(name, sex, age, country) 
 
if __name__ == "__main__": 
    readXLS("./test_read.xls");

Very easy, it should be noted that xlrd currently only supports MS Excel version 95-03, so you need to check your word version before using it.


Related articles: