Python 自动化操作 Excel - 01 - xlrd 原创

Python 自动化操作 Excel - 01 - xlrd

1.安装xlrd

pip install xlrd

pip3 install xlrd

2.建立表格

id数值列1数值列2
1AB
2AB
3AB
4AB
5AB
6AB

3.使用xlrd

import xlrd

# 1 读取xlsx
book = xlrd.open_workbook("./xlrd_excel.xlsx")

# 读取sheet
# 获取第1个sheet 方法1
sheet = book.sheets()[0]
# 方法2
# sheet = people.sheet_by_index(0)
# 方法3
# sheet = people.sheet_by_name("Sheet1")

# 读取表格
# sheet.cell_value(row, col)
data1 = sheet.cell_value(1, 0)
data2 = sheet.cell_value(1, 1)
print(f"data1: {data1}")
print(f"data2: {data2}")

# 读取所有的工作表
sheets = book.sheets()
for sheet in sheets:
    # 行数
    nrows = sheet.nrows
    # 列数
    ncols = sheet.ncols
    for row in range(0, nrows):
        for col in range(0, ncols):
            print(sheet.cell_value(row, col))

# 读入日期
time_value1 = sheet.cell_value(1, 6)
time_value2 = sheet.cell_value(2, 6)
# 将读入的日期转换为元组的形式
# (2019, 5, 6, 12, 10, 32)
time_tuple = xlrd.xldate_as_tuple(time_value1, 0)

# 将日期数据转换为datetime对象
time_datetime = xlrd.xldate_as_datetime(time_value1, 0)
# 将datetime对象格式化转化为对应的字符串
# 2019-05-06
time_str = time_datetime.strftime("%Y-%m-%d %H:%M:%S")

4.代码下载

GitHub点个star 非常感谢!
代码下载: Python 自动化操作 Excel

posted @   武子康  阅读(0)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示