惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
博客园 - 司徒正美
WordPress大学
WordPress大学
爱范儿
爱范儿
小众软件
小众软件
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
罗磊的独立博客
博客园_首页
V
V2EX
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
MyScale Blog
MyScale Blog
IT之家
IT之家
H
Help Net Security
Blog — PlanetScale
Blog — PlanetScale
Microsoft Security Blog
Microsoft Security Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recent Announcements
Recent Announcements
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
人人都是产品经理
人人都是产品经理

博客园 - Chen.HJ

python用正则对字符串进行运算 Nginx安装和遇到过的坑 Redis安装与常用命令 Nginx、Tomcat和Redis配置文件说明 python + selenium 获取标签文本的为空解决办法 Python使用paramiko的SFTP get或put整个目录 Linux系统性能监控工具nmon python+selenium个人学习笔记11-登录封装与调用 python+selenium+unittest测试框架4-邮件发送最新测试报告 python+selenium+unittest测试框架3-项目构建和发送邮件 python+selenium+unittest测试框架2-装饰器@classmethod python+selenium+unittest测试框架1-unittest单元测试框架和断言 python+selenium个人学习笔记10-调用JavaScript和截图 python+selenium个人学习笔记9-文件上传和cookie操作 python+selenium个人学习笔记8-获取信息和勾选框 python+selenium个人学习笔记7-警告框处理和下拉框选择 python+selenium个人学习笔记6-元素等待 python+selenium个人学习笔记5-多窗口和多表单切换 python+selenium个人学习笔记4-鼠标和键盘操作
Python读取Excel
Chen.HJ · 2019-02-13 · via 博客园 - Chen.HJ

一、基础操作

import xlrd
#打开Excel表格
data = xlrd.open_workbook(r"G:\Users\user.xlsx")
#获取目标EXCEL文件sheet名
print(data.sheet_names())
#通过索引顺序获取
#table = data.sheets()[0]
#通过索引顺序获取
#table = data.sheet_by_index(0)
# 通过名称获取 
table = data.sheet_by_name(u'Sheet1')
# 获取总行数
nrows = table.nrows
# 获取总列数
ncols = table.ncols
# 获取第一行值
print(table.row_values(0))
# 获取第二列值
print(table.col_values(1)) 
# 获取第二行第一列单元格内容
print(table.cell_value(1,0))  

二、封装读取Excel

# coding:utf-8
import xlrd

class DataTest:

    def __init__(self, filepath, sheetindex=0):
        self.data = xlrd.open_workbook(filepath)
        self.table = self.data.sheets()[sheetindex]
        self.rows = self.table.nrows
        self.cols = self.table.ncols
        #将第一行的值作为key值,当选中的sheet总行数小于或等于1时提示
        if self.rows<=1:
            print("选中的sheet表格总行数小于1或者等于1,请检查并录入测试数据或者选择其他sheet")
        else:
            self.keys = self.table.row_values(0)

    def dataddt(self):
        if self.rows<=1:
            pass
        else:
            l = []
            x = 1
            for i in range(self.rows-1):
                d = {}
                #从第二行开始获取对应的values值
                values = self.table.row_values(x)
                for j in range(self.cols):
                    d[self.keys[j]] = values[j]
                l.append(d)
                x +=1
            return l
        
if __name__ == "__main__":
    file = r"C:\Users\user.xlsx"
    date = DataTest(file)
    test = date.dataddt()
    print(test[0]["username"])
    print(test[1]["password"])
    print(test[2]["test"])