python for循环读取excel表格

下面代码复制按照自己的文件目录换掉就能运行,具体怎么用这些数据还要根据实际情况来。关于最后两行打印编码问题百度了很多也没有解决,不过并不影响实际的操作。本人试了一下,支持.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)))
  • 9
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值