python3安装xlrd模块_Python3学习 xlrd模块

xlrd模块是用来读取excel的第三方模块,需要下载安装后才能使用。新建一个excel,随便填充一些数据用来测试下。

按 Ctrl+C 复制代码

按 Ctrl+C 复制代码

在打印整行数据和整列数据的时候,合并的单元格,只会在合并的第一行或者第一列会有数据,之后打印出来都是空白。另外打印的日期时间也是错误的。

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

import xlrd

exce = xlrd.open_workbook('C:/Users/ms/Desktop/test_xlrd.xlsx')

sheet1 = exce.sheet_by_name('Sheet1')

print(sheet1.cell(4,0).value)

print(sheet1.cell(3,0).value)

print(sheet1.cell(3,2).value)

print(sheet1.cell(3,1).value)

先看合并单元格,这个没有任何技巧。只能获取 合并行单元格读取行的第一个索引,合并列单元格读取列的第一个索引。这样才能读到值,读错了就是空值。

但是合并单元格可能是读到空值,excel本身也可能就存在空值。要怎么获取单元格所谓的‘第一行或列的索引的’,这需要事先知道哪些单元格是合并的

print(sheet1.merged_cells)

使用merged_cells可以获得合并单元格。返回的参数(row,row_range,col,col_range),返回的是行数索引,行数索引范围,列数索引,列数索引范围。注意这里返回的应该都是索引。

根据返回的这四个值可以计算出合并单元格范围。计算时不需要把范围算进去,比如(3,5,0,1)行数索引就是3,4.对应excel行数就是第四行,第五行。列数所以就是0,也就是第一列

而在取所谓的第一行或第一列索引时候,直接从返回的四个参数中,取第一个和第三个就行了。可以对照上面的代码。对比下。

也可以封装成一个方法

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

import xlrd

exce = xlrd.open_workbook('C:/Users/ms/Desktop/test_xlrd.xlsx')

sheet1 = exce.sheet_by_name('Sheet1')

def row_col(sheet):

merge = []

for(row,row_range,col,col_range) in sheet.merged_cells:

merge.append([row,col])

for index in merge:

print(sheet.cell(index[0],index[1]).value)

row_col(sheet1)

再来看日期格式

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

import xlrd

exce = xlrd.open_workbook('C:/Users/ms/Desktop/test_xlrd.xlsx')

sheet1 = exce.sheet_by_name('Sheet1')

#处理单元格内容为data格式的数据

print(xlrd.xldate_as_datetime(sheet1.cell(2,2).value,0)) #转换成日期格式

print(xlrd.xldate_as_tuple(sheet1.cell(2,2).value,0)) #返回元组

有两种处理方式,一种转换成日期,一种是转换成元组

#如果ctype等于3,就用时间格式处理

def xldate_datetime(sheet,row,col):

if(sheet.cell(row,col).ctype==3):

date_value = xlrd.xldate_as_datetime(sheet.cell(row,col).value,0)

return date_value

print(xldate_datetime(sheet1,2,2))

可以简单封装成一个方法、

你可能感兴趣的:(python3安装xlrd模块)