python之xlrd

python处理excel的模块,xlrd读取excel,xlwt写入excel

一、安装

pip install xlrd

二、使用

1. 打开excel,得到Book对象

import xlrd
rb = xlrd.open_workbook(r'E:\python\test.xlsx', formatting_info=True)
# excel文件被打开为一个Book对象,即 rb(xlrd.book.Book类)
sheets = rb.sheet_names()
# 获取Book对象的属性:包含所有sheet表名的列表(xlrd.book.Book.sheet_names)

2. 指定sheet工作表(基于Book对象),得到Sheet对象

sheet1 = rb.sheet_by_index(0)
# 通过索引获取第0个工作表,并打开为Sheet对象(xlrd.sheet.Sheet类)
sheet2 = rb.sheet_by_name('sheet2')
# 直接通过工作表名称打开为Sheet对象,如果打开的是同一个表,则和上面的方法获取到的对象完全等价==

3. Sheet对象的属性

print(sheet1.name, sheet1.nrows, sheet1.ncols)
# sheet1的名称、行数、列数
print(sheet1.row_values(0), sheet1.col_values(0), sheet1.cell_value(0, 0))
# sheet1的某一行/某一列所有值的列表,某行某列的值

4. Cell对象(基于Sheet对象)的属性

cell_0_0 = sheet1.cell(0, 0)
# sheet1的某行某列的Cell对象(xlrd.sheet.Cell类)
row_0 = sheet1.row(0)
col_0 = sheet1.col(0)
# sheet1的某一行/某一列所有cell对象的列表
print(cell_0_0.value)
# cell_0_0对象的值
print(cell_0_0.ctype)
# cell_0_0对象的类型
# _0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error

5. 日期的处理

excel中的日期时间通过xlrd读取到数据后,会转换成一串数字
2018/07/10会转换为43291.0
2018/7/10  18:15:02 会转换成43291.76043981482
cell_0_0_tuple = xlrd.xldata_as_tuple(cell_0_0.value, datemode=0)
# 首先要判断ctype属于日期,然后才能转换为tuple(年,月,日,时,分,秒)
# datemode在此处的含义是从1900年开始,如果等于1,则是从1904年开始(使用0即可)

from datetime import datetime, date
date(*cell_0_0_tuple[:3]).strftime('%Y/%m/%d')
# 使用date模块,将tuple的年月日转换为date对象(只支持三位参数),使用strftime方法格式化。

6. 合并单元格数据处理

merged = sheet1.merged_cells

返回结果是一个由tuple组成的list,每个tuple含四个元素,形成一个合并单元格的矩阵。
[(rl1, rh1, cl1, ch1), (rl2, rh2, cl1, ch2)] ; l为开始,h-1为结束
(4,5,1,3), 合并了第4行(实际第五行,不赘述)到第4行,第1列到第2列的数据。
posted @ 2020-07-20 16:09  第十一个程序员  阅读(2006)  评论(0编辑  收藏  举报