BZ易风

导航

 
import xlrd //导入模块
filename='路径/文件名'  //文件路径、名称
python读取excel中单元格的内容返回的有5种类型,即ctype:0. empty(空的),1 string, 2 number, 3 date, 4 boolean, 5 error
data = xlrd.open_workbook(filename)#文件名以及路径,如果路径或者文件名有中文给前面加一个r拜师原生字符。
 1.获取book中一个工作表
table=data.sheets()[0] #[0]取excel里面的第一个表
table = data.sheet_by_index(sheet_indx)) #通过索引顺序获取

table = data.sheet_by_name(sheet_name)#通过名称获取

以上三个函数都会返回一个xlrd.sheet.Sheet()对象

names = data.sheet_names()    #返回book中所有工作表的名字

data.sheet_loaded(sheet_name or indx)   # 检查某个sheet是否导入完毕
2.行/列操作
nrows = table.nrows  #获取该sheet中的有效行数
ncols = table.ncols   #获取列表的有效列数
table.row(rowx)  #返回由该行中所有的单元格对象组成的列表
table.col(colx, start_rowx=0, end_rowx=None)  #返回由该列中所有的单元格对象组成的列表
table.row_slice(rowx)  #返回由该列中所有的单元格对象组成的列表
table.col_slice(colx, start_rowx=0, end_rowx=None)  #返回由该列中所有的单元格对象组成的列表
table.row_types(rowx, start_colx=0, end_colx=None) #返回由该行中所有单元格的数据类型组成的列表 
table.col_types(colx, start_rowx=0, end_rowx=None)    #返回由该列中所有单元格的数据类型组成的列表
table.row_values(rowx, start_colx=0, end_colx=None) #返回由该行中所有单元格的数据组成的列表 
table.col_values(colx, start_rowx=0, end_rowx=None)   #返回由该列中所有单元格的数据组成的列表
table.row_len(rowx) #返回该列的有效单元格长度
3.单元格操作
table.cell(rowx,colx)   #返回单元格对象

table.cell_type(rowx,colx)    #返回单元格中的数据类型

table.cell_value(rowx,colx)   #返回单元格中的数据

table.cell_xf_index(rowx, colx)   #?

 python解决open()函数、xlrd.open_workbook()函数文件名包含中文,sheet名包含中文报错的问题

  1、使用open()函数、xlrd.open_workbook()函数打开文件,文件名若包含中文,会报错找不到这个文件或目录。 

  2、获取sheet时若包含中文,也会报错。

file = open(filename,'rb') #打开文件

workbook = xlrd.open_workbook(filename)  #打开excel文件

 sheet = workbook.sheet_by_name(sheetname) #获取sheet

解决方案:

对参数进行转码即可。如:

1.filename = filename.decode('utf-8')

2.filename = unicode(filename,'utf-8') #不赞成直接使用




posted on 2018-10-23 09:51  BZ易风  阅读(411)  评论(0编辑  收藏  举报