python如何处理表格?


当前第2页 返回上一页

详细代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import xlrd

from datetime import date,datetime

file = 'test3.xlsx'

def read_excel():

wb = xlrd.open_workbook(filename=file)#打开文件

print(wb.sheet_names())#获取所有表格名字

sheet1 = wb.sheet_by_index(0)#通过索引获取表格

sheet2 = wb.sheet_by_name('年级')#通过名字获取表格

print(sheet1,sheet2)

print(sheet1.name,sheet1.nrows,sheet1.ncols)

rows = sheet1.row_values(2)#获取行内容

cols = sheet1.col_values(3)#获取列内容

print(rows)

print(cols)

print(sheet1.cell(1,0).value)#获取表格里的内容,三种方式

print(sheet1.cell_value(1,0))

print(sheet1.row(1)[0].value)

运行结果如下:

bf3bdd416779fba08553835c6f68d27.png

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

别急,我们来一一解决这两个问题:

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才能开始操作。

详细代码如下:

1

2

3

4

5

6

7

import xlrd

from datetime import date,datetime

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

date_value = xlrd.xldate_as_tuple(sheet1.cell_value(1,2),wb.datemode)

print(date_value)

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

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

0dade1f0acb52ebdf3c7bb1efd75c4e.png

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列合并。

详细代码如下:

1

2

3

print(sheet1.merged_cells)print(sheet1.cell_value(1,3))

print(sheet1.cell_value(4,3))

print(sheet1.cell_value(6,1))

18fa2af4c3e2b37bd0cdcd5a5e3035f.png

发现规律了没?是的,获取merge_cells返回的row和col低位的索引即可! 于是可以这样批量获取:

详细代码如下:

1

2

3

4

5

6

merge = []

print(sheet1.merged_cells)

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

merge.append([rlow,clow])

for index in merge:

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

运行结果跟上图一样,如下:

94ff412e6221cf75ee5fee246b805a4.png

推荐教程:《python》

以上就是python如何处理表格?的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python实现简单淘宝秒杀功能

怎么保存Python代码?

Python使用matplotlib绘制饼图

flask 和 django 区别

Python循环10次怎么写

Python如何将数据导出excel的技巧分享

Python中保留两位小数怎么表示

为何选择Python进行数据分析

Python学习之代理模式

Python中怎么安装pip工具?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...