【python】 xlrd的使用
2012-11-25 16:04:29
分类: Python/Ruby
详细代码:
点击(此处)折叠或打开
- Demo:
- 1. open a xls file
- 2. read a sheet
- 3. read a cell or row or col
- 4. modify the cell
- '''
-
- import xlrd
- import os
-
-
- class XlsEngine():
- """
- The XlsEngine is a demo class for excel openration
- Just for some basic test or the using or the 3rd class in python
- """
- def __init__(self,__name):
- # define class variable
- self.xls_name = __name
- self.xlrd_object = None
- self.isopenfailed = True
- def open(self):
- try:
- self.xlrd_object = xlrd.open_workbook(self.xls_name)
- self.isopenfailed = False
- pass
- except :
- self.isopenfailed = True
- self.xlrd_object = None
- print("open %s failed \n"%self.xls_name)
- pass
- finally:
- '''
- do nothing
- '''
- pass
- return [self.isopenfailed,self.xlrd_object]
-
- def dump_sheet(self):
- if self.isopenfailed == False:
- '''
- dump the sheet
-
- usging for getting the sheet
- table = data.sheets()[0]
- table = data.sheet_by_index(0)
- table = data.sheet_by_name(u'Sheet1')
- '''
- for name in self.xlrd_object.sheet_names():
- table = self.xlrd_object.sheet_by_name(name)
- print("sheet %s rownums=%d colnums=%d"%(name,table.nrows,\
- table.ncols))
- else:
- print("file %s is not open \n"%self.xls_name)
-
- def dump_cell(self,sheet_index,cell_row,cell_col):
- try:
- table=self.xlrd_object.sheet_by_index(0)
- value=table.cell(cell_row,cell_col).value
- print("value=%d"%value)
- pass
- except:
- pass
-
-
- def modify_cell(self,sheet_index,cell_row,cell_col,__value):
- try:
- table=self.xlrd_object.sheet_by_index(0)
- value=table.cell(cell_row,cell_col).value
- print("value=%d"%value)
- table.put_cell(cell_row,cell_col,1,__value,0)
- value=table.cell(cell_row,cell_col).value
- print("value=%d"%value)
- pass
- except:
- print("error")
-
- pass
-
-
-
-
-
-
- if __name__ == '__main__':
- tt=XlsEngine('D:\\tt.xls
以下为参考博文:
python操作Excel读写--使用xlrd
一、安装xlrd模块
到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境。
二、使用介绍
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')#通过名称获取
获取整行和整列的值(数组)
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.col(1)[0].value
简单的写入
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 #单元格的值'