python read and write excel file

Create a separate class to store the operations of reading and writing excel. The commented out at the bottom is the write operation, which can be used! (note the subscripts, similar to arrays)

# -*- 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_)

If you need to read, call the readExcel method in the new class, then write:

# -*- 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]  # 谷歌浏览器驱动路径

Remark:

1. The "configuration" above is a sheet in an excel sheet. The following method to read the content in that sheet is as above.

 

If you want to get a row of data, the method is as follows:

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)
# 将分号插入到里面 最后出现的效果就是  [email protected];[email protected];[email protected]
for i in receivers:
    if (len > 1):
        email_receivers = email_receivers + i
        email_receivers += ";"
        len = len - 1
    else:
        email_receivers = email_receivers + i

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326951109&siteId=291194637