算法练习之读取excel 指定日期的后3天的数据
需求来源:某知乎球友提问 如何用python对excel实现读取指定日期的数据? 保留第一行表头,保留前2列,读取当天及往后3天(一共4天包含当天)的数据
直接上python3代码:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/12/1 19:08
# @Author : Clover
# @Email : ft_clover@163.com
# @File : ReadExcel.py
#获取当前时间
import xlrd
from xlrd import xldate_as_tuple
import datetime
#读取Excel文件
file=u"临时.xlsx"#注意读中文文件名稍微处理一下
data=xlrd.open_workbook(file)
#Sheet1
table = data.sheet_by_index(0)#按照索引读Excel文件
firstrows=table.row_values(0)
print("读取第一行:"+str(firstrows))
totalRows = table.nrows #行
totalCols = table.ncols #列
print ("总行数"+str(totalRows),"总列数"+str(totalCols))
#可修改为获取当前时间,此处写死了
nowDate = '2020-12-03'
targetCol = 0
#读取第0行 第i列的数据:
for i in range(0, totalCols):
cType = table.cell_type(0,i) #读取第0行,第i列的单元格数据类型
# ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
if cType==3:
result=table.cell_value(0, i) #读取第0行,第i列的单元格数据
date = datetime.datetime(*xldate_as_tuple(result, 0)).strftime('%Y-%m-%d')
if(nowDate <= date):
print(date)
targetCol = i
break
excelMap = {}
for i in range(0, totalRows):
rowList = []
# 读取第一列 # 可修改为读取前2列 把0修改为1即可
cellValueZero = table.cell_value(i, 0)
rowList.append(cellValueZero)
##通过修改totalCols的值,获取当前时间后几天的数据,如targetClo+4,就是获取当前日期后3天的数据,包含当天
for j in range(targetCol, totalCols):
cType = table.cell_type(i, j)
cellValue = table.cell_value(i, j)
if cType == 3:
cellValue = datetime.datetime(*xldate_as_tuple(cellValue, 0)).strftime('%Y-%m-%d')
rowList.append(cellValue)
# excelMap[str(i)+"行"] = rowList
excelMap[table.cell_value(i,0)]=rowList
print(excelMap)
测试数据:

将
cellValueZero = table.cell_value(i, 0) 修改为:cellValueZero = table.cell_value(i, 1)
for j in range(targetCol, totalCols): 修改为for j in range(targetCol,targetCol+4):
执行结果为:



浙公网安备 33010602011771号