单独新建一个class类存放读取和写入excel的操作,最下方注释掉的是写入操作,可以使用!(要注意的是下标号,类似于数组)
# -*- coding: utf-8 -*-
from xlutils.copy import copy
import xlrd
path = r'E:\pyworkspase\data\data.xls' # Excel路径
# 读取Excel表(传入的name代表sheet)
def readExcel(name):
wb = xlrd.open_workbook(path) # 打开Excel
sh = wb.sheet_by_name(name) # 读取哪个表
row = sh.nrows # 共有多少行
col = sh.ncols # 共有多少列
ss = []
for i in range(0, row):
s = sh.row_values(i)
ss.append(s)
return ss # 返回类型为list[[],[],[]],一行为一个小集合
# 写入Excel表
# 写入为list[[row,col,message],[row,col,message],[row,col,message]]格式
def writeExcel(name, list_):
# 打开已有的Excel,formatting_info=True,得以保存之前数据的格式
rb = xlrd.open_workbook(path, formatting_info=True)
wbk = copy(rb) # copy去从打开的xlrd的Book变量中,拷贝出一份,成为新的xlwt的Workbook变量
sheet1 = wbk.get_sheet(name)
for i in range(0, len(list_)):
sheet1.write(list_[i][0], list_[i][1], list_[i][2])
wbk.save(path) # 保存Excel表
#调用写入excel的方法
# if __name__ == '__main__':
# list_ = [[5, 0, '啦啦啦5'], [5, 1, '啦啦啦55']]
# print(list_)
# writeExcel('MySQL_config', list_)
需要读取的话,在新的class类中调用这个readExcel方法,那么就要写:
# -*- coding: utf-8 -*-
from utils import rwExcel
# excel_path = r'E:\pyworkspase\data\data.xls' # 读取Excel的路径
list_ = rwExcel.readExcel('配置') # 读取配置表
URL = list_[0][0] # 测试网址
Browser = list_[1][0] # 浏览器。。。。谷歌-chrome,IE-ie,火狐-firefox
firefoxDriver = list_[2][0] # 火狐浏览器驱动路径
chromeDriver = list_[3][0] # 谷歌浏览器驱动路径
备注:
1.上方的“配置”是一个excel表中的一个sheet。下面读取那个sheet中的内容方法如上。
如果想要获取一行数据,方法如下:
email_config = rwExcel.readExcel('email_config') # 获取email配置
email_server = email_config[0][2] # email_server
email_user = email_config[1][2] # user
email_pass = email_config[2][2] # password
email_num = email_config[3][2] # 端口号
# email_receivers = email_config[4][1] # 接受邮件人
email_receivers = "" # 接受邮件人
receivers = [] # 接受邮件人
for i in range(1, len(email_config[3])):
receivers.append(email_config[4][i])
len = len(receivers)
# 将分号插入到里面 最后出现的效果就是 111111@qq.com;222222@qq.com;333333@qq.com
for i in receivers:
if (len > 1):
email_receivers = email_receivers + i
email_receivers += ";"
len = len - 1
else:
email_receivers = email_receivers + i