Python uses a third-party library xlrd to read the Excel example, pythonxlrd
This article describes how to use xlrd to read the content in an Excel table. xlrd is a third-party library, so we need to install xlrd before use. In addition, we generally use xlwt to write Excel, so the next article will introduce how to use xlwt to write Excel. Xlrd download: xlrd 0.8.0
Install xlrd
To install xlrd, you only need to run setup. In addition, you can directly decompress it to your project, or directly use
Xlrd API
Obtain an Excel file, which is called a work book.
Copy codeThe Code is as follows:
Open_workbook (file_name)
You can obtain a specified Sheet in either of the following ways:
Copy codeThe Code is as follows:
Sheet = xls. sheet_by_index (sheet_no)
Sheet = xls. sheet_by_name (sheet_name)
Get the value of the whole row and the whole column (array)
Copy codeThe Code is as follows:
Sheet. row_values (I)
Sheet. col_values (I)
Obtain the total number of rows and total number of Columns
Copy codeThe Code is as follows:
Nrows = sheet. nrows
Ncols = sheet. ncols
Use xlrd
Using xlrd here is a simple example:
Copy codeThe Code is 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 t 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: # interpret 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 ");
It's easy. It should be noted that xlrd currently only supports MS Excel in, so you need to check your word version before using it.