Python:使用第三方库xlrd来读Excel

本篇文章介绍如何使用xlrd来读取Excel表格中的内容,xlrd是第三方库,因此在使用前咱们须要安装xlrd。另外咱们通常会使用xlwt来写Excel,因此下一篇文章咱们会来介绍如何使用xlwt来写Excel。html

        xlrd下载:xlrd 0.8.0python

安装xlrd数组

        安装xlrd,只需运行setup便可,另外你也能够直接解压缩到你的project中,也能够直接用。ide

xlrd的APIpost

        获取Excel,这里称之为work bookunix

Python代码code

  1. open_workbook(file_name) 

        获取指定的Sheet,有两种方式htm

Python代码对象

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

         获取整行和整列的值(数组)ip

Python代码

  1. sheet.row_values(i)  
  2. sheet.col_values(i)  

        获取总行数和总列数

Python代码

  1. nrows = sheet.nrows  
  2. ncols = sheet.ncols  

使用xlrd

        使用xlrd这里就用一个简单的例子示例下:

Python代码

  1. # -*- coding: utf-8 -*-
  2. '''''
  3. Created on 2012-12-14
  4. @author:  walfred
  5. @module: XLRDPkg.read
  6. @description:
  7. '''
  8. import os 
  9. import types 
  10. import xlrd as ExcelRead 
  11. def readXLS(file_name): 
  12. if os.path.isfile(file_name): 
  13. try: 
  14.             xls = ExcelRead.open_workbook(file_name) 
  15.             sheet = xls.sheet_by_index(0) 
  16. except Exception, e: 
  17. print "open %s error, error is %s" %(file_name, e) 
  18. return
  19.     rows_cnt = sheet.nrows 
  20. for row in range(1, rows_cnt): 
  21.         name = sheet.row_values(row)[0].encode("utf-8").strip() 
  22.         sex = sheet.row_values(row)[1].encode("utf-8").strip() 
  23.         age = sheet.row_values(row)[2] 
  24. if type(age) is types.FloatType:#判读下类型
  25.             no = str(int(age)) 
  26. else: 
  27.             age = no.encode("utf-8").strip() 
  28.         country = sheet.row_values(row)[3].encode("utf-8").strip() 
  29. print "Name: %s, Sex: %s, Age: %s, Country: %s" %(name, sex, age, country) 
  30. if __name__ == "__main__": 
  31.     readXLS("./test_read.xls"); 

        很easy吧,须要说明的是,目前xlrd只支持95-03版本的MS Excel,因此使用以前须要核对本身的word对象。

相关文章
相关标签/搜索