This article describes how to use XLRD to read the contents of an 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 the next article we will explain how to use XLWT to write Excel. XLRD Download: xlrd 0.8.0
Install XLRD
Install XLRD, just run Setup, and you can also directly unzip to your project, or you can use
API for XLRD
Get Excel, called work book here
Copy Code code as follows:
Open_workbook (file_name)
There are two ways to get the specified sheet
Copy Code code as follows:
Sheet = Xls.sheet_by_index (sheet_no)
Sheet = xls.sheet_by_name (sheet_name)
Gets the value of an entire row and column (array)
Copy Code code as follows:
Sheet.row_values (i)
Sheet.col_values (i)
Get total number of rows and columns
Copy Code code as follows:
nrows = Sheet.nrows
Ncols = Sheet.ncols
using XLRD
Using XLRD here is a simple example of the example:
Copy Code code as follows:
#-*-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]
The If type (age) is types. Floattype: #判读下类型
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");
It's easy to note that currently XLRD only supports version 95-03 of Ms Excel, so you'll need to check your version of Word before using it.