设为首页 加入收藏

TOP

python读取excel文件
2017-09-30 17:17:10 】 浏览:562
Tags:python 读取 excel 文件

一、xlrd的说明

xlrd是专门用来在python中读取excel文档的模块,使用前需要安装。

可以到这https://pypi.python.org/pypi/xlrd进行下载tar.gz文件,然后解压缩安装,在cmd命令窗口中切换到解压后的文件夹中,使用

python setup.py install

进行安装。

方法二、

使用pip进行安装

pip install xlrd

二、使用介绍

1导入模块

  import xlrd

2 打开excel文件

  data = xlrd.open_workbook('excelFile.xls')

3 获取一个工作表方法

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

  table = data.sheet_by_index(0) #通过索引顺序获取 

  table = data.sheet_by_name(u'Sheet1')#通过名称获取
 
4 获取整行或整列的值,-->返回数组
  table.row_values(i)
  table.col_values(i)
 
5 获取行数和列数
  nrows = table.nrows
  ncols = table.ncols
 
6 循环表获取行数据,--->返回数据
    for i in range(nrows ):
        print table.row_values(i)
 
7 单元格
  cell_A1 = table.cell(0,0).value
  cell_C4 = table.cell(2,3).value
 
也可以使用行列号进行索引
  
cell_A1 = table.row(0)[0].value
  
cell_A2 = table.col(1)[0].value
 
 
8 sheet的一些属性
 
  name获取此时工作表的名字,print table.name
 
  
 
 
 三、添加数据到excel文件
 
  要使用xlutils包里面的copy函数,将xlrd打开的workbook转换到xlwt可以写的状态
  
def writeHeaderToXls(self):
        oldwb = xlrd.open_workbook(self.resultFileName,formatting_info=True)
        os.remove(self.resultFileName)
        newwb = copy(oldwb)
        
        for sheetindex in range(oldwb.nsheets):
            oldsheet = oldwb.sheet_by_index(sheetindex)
            colLength = oldsheet.ncols
            newsheet = newwb.get_sheet(sheetindex)
            for i in range(colLength):
                title = "level %d th"%(i+1)
                newsheet.row(0).write(i,title)
                
        newwb.save(self.resultFileName)

 

 
 
 

  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python读写csv文件 下一篇Python自动化运维之1、Python入门

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目