下面代码复制按照自己的文件目录换掉就能运行,具体怎么用这些数据还要根据实际情况来。关于最后两行打印编码问题百度了很多也没有解决,不过并不影响实际的操作。本人试了一下,支持.xls和.xlsx
# coding=utf-8
from datetime import datetime
import xlrd
# 读取表
from xlrd import xldate_as_tuple
book = xlrd.open_workbook('example.xls')
# 获取第一个sheet页
sheet1 = book.sheets()[0]
# 获取总行数
rows = sheet1.nrows
# 获取总列数
cols = sheet1.ncols
for i in range(0, rows):
#操作
for j in range(0, cols):
# 操作
ctype = sheet1.cell(i, j).ctype
cell = sheet1.cell_value(i, j)
if ctype == 2 and cell % 1 == 0: # 如果是整形
cell = int(cell)
elif ctype == 3:#如果是日期型
# 转成datetime对象
date = datetime(*xldate_as_tuple(cell, 0))
cell = date.strftime('%Y/%d/%m %H:%M:%S')
elif ctype == 4: #如果是boolean型
cell = True if cell == 1 else False
print (cell)
# print ('第{}行第{}列数据'.format(i, j).encode('utf-8'), str(sheet1.cell_value(int(i), int(j))).encode('utf-8'))
# print('第{}行第{}列数据:'.format(i,j),sheet1.cell_value(int(i), int(j)))