Python模块之xlrd(读取excel中的数据)的用法介绍

Python 1700℃

xlrd是python环境下对excel中的数据进行读取的一个模块,简单易用,可以进行的操作有:

  • 读取工作表有效的行数、列数
  • 读取指定行、列的所有单元格的值
  • 读取指定单元格的值
  • 读取指定单元格的数据类型

1.安装xlrd

pip install xlrd

2.打开excel,得到工作薄(Book)对象

#导入xlrd模块
import xlrd
#excel文件被打开为一个Book对象(xlrd.book.Book)
workBook = xlrd.open_workbook(r'D:\test.xlsx', formatting_info=True)
#获取Book对象的属性:所有sheet表名的列表(xlrd.book.Book.sheet_names)
sheets = workBook.sheet_names()

3.得到Sheet对象

#基于上面的Book对象,得到Sheet对象(xlrd.sheet.Sheet),有两种方法:
#方法1:通过指定索引获取
sheet1 = workBook.sheet_by_index(0)
#方法2:通过工作表名获取
sheet2 = workBook.sheet_by_name('sheet2')

4.获取表名、行数、列数、值

#基于上面的Sheet对象,可得到如下属性:
#表名
print(sheet1.name)
#有效行数
print(heet1.nrows)
#有效列数
print(sheet1.ncols)
#指定行的所有值
print(sheet1.row_values(0))
#指定列的所有值
print(sheet1.col_values(0))
#指定单元格的值
print(sheet1.cell_value(0,0))

5.获取Cell对象

#基于上面的Sheet对象,获取Cell对象(xlrd.sheet.Cell)
cell0 = sheet1.cell(0,0)
#获取某一行所有cell对象的列表
row_0 = sheet1.row(0)
#获取某一列所有cell对象的列表
col_0 = sheet1.col(0)

6.获取单元格值、数据类型

#基于上面的Cell对象,获取单元格的值
print(cell0.value)
#获取单元格的数据类型
print(cell_0_0.ctype)
#0 empty,1 string,2 number,3 date,4 boolean,5 error

7.日期的处理

#excel中的日期时间通过xlrd读取到数据后,会转换成一串数字,如:
#2018/07/10会转换为43291.0
#2018/7/10 18:15:02 会转换成43291.76043981482
#正确的做法是:先判断ctype是日期,再转换为tuple(年,月,日,时,分,秒)
if cell_0_0.ctype==3:
	cell_0_0_tuple = xlrd.xldata_as_tuple(cell_0_0.value, datemode=0)
#datemode在此处的含义是从1900年开始,如果等于1,则是从1904年开始
#最后使用date模块,将tuple的换为date对象(只支持三位参数),使用strftime方法格式化。
from datetime import datetime, date
date(*cell_0_0_tuple[:3]).strftime('%Y/%m/%d')

8.获取单元内容为number的方式(转为整型)

if sheet1.cell(3, 5).ctype == 2:
    print(sheet1.cell(3, 5).value)	#输出133111.0
    num_value = int(sheet1.cell(3, 5).value)
    print(num_value)			#输出133111

转载请注明:零五宝典 » Python模块之xlrd(读取excel中的数据)的用法介绍