您的位置:首页 > 编程语言 > Python开发

python 读取excel数据

2016-08-24 10:39 711 查看
1.安装 xlrd

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


  下载xlrd后,解压,CMD命令切到xlrd目录下:
 
 


 
 输入python 安装命令:

 
 python setup.py install 

 
 


如果python中安装了pip,也可以使用pip进行安装,在cmd命令行中输入:pip
install xlrd 

2.使用

原文地址:http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html

导入模块

import
xlrd

打开excel文件读取数据

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

读取工作表

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

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

table
= data.sheet_by_name(u'Sheet1') # 通过名称获取

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

table.row_values(i)

table.col_values(i)

获取行数和列数

nrows
= table.nrows

ncols
= table.ncols

循环行列数据

for
i in range(nrows):

 
print table.row_values(i)

单元格

cell_A1
= table.cell(0,0).value

cell_C4
= table.cell(2,3).value

使用行列索引

cell_A1
= table.row(0)[0].value

cell_A2
= table.row(1)[0].value

写入

row
= 0

col
= 0 

# 类型 empty:0,string:1,number:2,data:3,boolean:4,error:5

ctype=1

value
= '单元格的值'

xf = 0

table.put_cell(row,col,ctype,value,xf)

table.cell(0,0)

table.cell(0,0).value

# -*- coding: utf-8 -*-

import xlrd

def excel_data(file= 'abc.xls'):
try:
# 打开Excel文件读取数据
data = xlrd.open_workbook(file)
# 获取第一个工作表
table = data.sheet_by_index(0)
# 获取行数
nrows = table.nrows
# 获取列数
ncols = table.ncols
# 定义excel_list
excel_list = []
for row in range(1, nrows):
for col in range(ncols):
# 获取单元格数据
cell_value = table.cell(row, col).value
# 把数据追加到excel_list中
excel_list.append(cell_value)
return excel_list
except Exception, e:
print str(e)

if __name__ == "__main__":
list = excel_data()
for i in list:
print i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: