python操作读取excel表格

python读excel——xlrd

一、安装xlrd模块

py -3 -m pipinstall xlrd 或者python –mpip install xlrd,如下图:


二、实际操作:

整体思路为à打开文件,选定表格,读取行列内容,读取表格内数据;

以下图为例:

1.打开文件:

data=xlrd.open_workbook(r"E:\pythonTester\info.xlsx")

2.选定表格:

  #print (data.sheet_names())   若有多个工作表,可通过此代码打印所有表格的名称

sheet1=data.sheet_by_index(0)          #索引读取

sheet2=data.sheet_by_name("年级")     #姓名读取

sheets=data.sheets()[0]                 #函数读取

3.统计表中的行数、列数:

   rows=sheet1.nrows

  cols=sheet1.ncols

4.打印表格中整行整列的内容

   print (sheet1.row_values(0))    #打印第一行的内容

   print (sheet1.col_values(1))     #打印第二列的内容

5.读取表格内的数据

   #按单元格读取

   print (sheet1.cell(0,1).value)   à第1行第2列中的内容

   print (sheet1.cell_value(0,1))

  

   #按列读取

   print (sheet1.col_value(1)[0])   à第2列第1行的内容

   

   #按行读取

   print (sheet1.row_value(1)[0])   à第2行第1列的内容

存在两个问题:上面的运行结果中红框框中的字段明明是出生日期,可显示的确实浮点数;同时合并单元格里面应该是有内容的,结果不能为空。

三、解决问题

1.python读取excel中单元格内容为日期的方式

python读取excel中单元格的内容返回的有5种类型,即上面例子中的ctype:

ctype : 0 empty,1 string,2 number, 3 date,4 boolean,5 error

即date的ctype=3,这时需要使用xlrd的xldate_as_tuple来处理为date格式,先判断表格的ctype=3时xldate才能开始操作。

import xlrd

from datetime import date,datetime

print (sheet1.cell(1,2).ctype)

data_value=xlrd.xldate_as_tuple(sheet1.cell(1,2).value,data.datemode)

print (data_value)

print (date(*data_value[:3]))

print ((date(*data_value[:3])).strftime('%Y%m%d'))

 

2.获取合并单元格的内容

在操作之前,先介绍一下merged_cells()用法,merged_cells返回的这四个参数的含义是:(row,row_range,col,col_range),其中[row,row_range)包括row,不包括row_range,col也是一样,即(1, 3,4, 5)的含义是:第1到2行(不包括3)合并,(7, 8, 2, 5)的含义是:第2到4列合并。

print (sheet1.merged_cells)

print (sheet1.cell_value(6,1))

print (sheet1.cell_value(4,3))

运行结果如下:

从上面可以发现,获取merged_cells返回的row和col低位的索引即可!然后可以批量获取,详细代码如下:

merge=[]

for (rlow,rhigh,clow,chigh) in sheet1.merged_cells:

    merge.append([rlow,clow])

此时merge为[[6, 1], [4, 3]]

for index in merge:

    #print (index[0],index[1])  #6 1;4 3

print (sheet1.cell_value(index[0],index[1]))

运行结果如下

猜你喜欢

转载自blog.csdn.net/weixin_37579123/article/details/80965906