---
title: "python操作Excel读写--使用xlrd"
author: "wait_miracle"
date: "2014-02-07T11:28:43Z"
tags: []
categories: ["移动开发"]
slug: "python-excel-xlrd"
draft: false
lastmod: "2014-02-07T15:02:50Z"
id: 2012028
url: "https://wait-miracle.iteye.com/blog/2012028"
---

一、安装xlrd模块

   到python官网下载[http://pypi.python.org/pypi/xlrd](http://pypi.python.org/pypi/xlrd)模块安装，前提是已经安装了python 环境。

本人安装的版本：0.9.2，适用2.7以上的python，在cmd窗口，切换路径至setup.py文件下，在cmd窗口输入“python setup.py install”命令。

二、使用介绍

  1.导入模块

      import xlrd

   2.打开Excel文件读取数据

       data = xlrd.open\_workbook('excelFile.xls')

   3.使用技巧

      &lt;1&gt;**获取一个工作表**

      table = data.sheets()\[0]          #通过索引顺序获取

 

        table = data.sheet\_by\_index(0) #通过索引顺序获取

        table = data.sheet\_by\_name(u'Sheet1')#通过名称获取

      &lt;2&gt;**获取整行和整列的值（数组）**

          table.row\_values(i)

          table.col\_values(i)

      &lt;3&gt;**获取行数和列数**

       nrows = table.nrows

         ncols = table.ncols

       

        &lt;4&gt;**循环行列表数据**

        for i in range(nrows ):

           print table.row\_values(i)

 

        **&lt;5&gt;单元格**

        cell\_A1 = table.cell(0,0).value

         cell\_C4 = table.cell(2,3).value

 

        **&lt;6&gt;使用行列索引**

          cell\_A1 = table.row(0)\[0].value

 

          cell\_A2 = table.col(1)\[0].value

 

        **&lt;7&gt;简单的写入**

         row = 0

            col = 0

 

\# 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

ctype = 1 value = '单元格的值'

 

xf = 0 # 扩展的格式化

 

table.put\_cell(row, col, ctype, value, xf)

 

table.cell(0,0)  #单元格的值'

 

table.cell(0,0).value #单元格的值'

 

 

三、Demo代码

   Demo代码其实很简单，就是读取Excel数据。

   

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
1 # -*- coding: utf-8 -*-  
2 import  xdrlib ,sys

3 import xlrd
 
4 def open_excel(file= 'file.xls'):
 
5     try:
 
6         data = xlrd.open_workbook(file)
 
7         return data
 
8     except Exception,e:
 
9         print str(e)

10 #根据索引获取Excel表格中的数据->参数:file：Excel文件路径;colnameindex：表头列名所在
    行的索引；by_index：表的索引
11 def excel_table_byindex(file= 'file.xls',colnameindex=0,by_index=0):

12     data = open_excel(file)

13     table = data.sheets()[by_index]

14     nrows = table.nrows #行数
15     ncols = table.ncols #列数
16     colnames =  table.row_values(colnameindex) #某一行数据 
17     list =[]

18     for rownum in range(1,nrows):

19 

20          row = table.row_values(rownum)

21          if row:
22              app = {}

23              for i in range(len(colnames)):

24                 app[colnames[i]] = row[i] 

25              list.append(app)

26     return list

27 

28 #根据名称获取Excel表格中的数据->参数:file：Excel文件路径;colnameindex：表头列名所
     在行的索引；by_name：Sheet1名称
29 def excel_table_byname(file= 'file.xls',colnameindex=0,by_name=u'Sheet1'):

30     data = open_excel(file)

31     table = data.sheet_by_name(by_name)

32     nrows = table.nrows #行数 
33     colnames =  table.row_values(colnameindex) #某一行数据 
34     list =[]

35     for rownum in range(1,nrows):

36          row = table.row_values(rownum)

37          if row:

38              app = {}

39              for i in range(len(colnames)):

40                 app[colnames[i]] = row[i]

41              list.append(app)

42     return list

43 

44 def main():

45    tables = excel_table_byindex()

46    for row in tables:

47        print row

48 

49    tables = excel_table_byname()

50    for row in tables:

51        print row

52 

53 if __name__=="__main__":

54     main()
```