用xlrd和xlwt读写excel
首先下载安装xlrd和xlwt这两个库。
1、打开excel
readbook = xlrd.open_workbook(r'\test\canying.xlsx')
2、获取读入的文件的sheet
sheet = readbook.sheet_by_index(1)#索引的方式,从0开始
sheet = readbook.sheet_by_name('sheet2')#名字的方式
3、获取sheet的最大行数和列数
nrows = sheet.nrows#行
ncols = sheet.ncols#列
4、获取某个单元格的值
lng = table.cell(i,3).value#获取i行3列的表格值
lat = table.cell(i,4).value#获取i行4列的表格值
5、打开将写的表并添加sheet
writebook = xlwt.Workbook()#打开一个excel
sheet = writebook.add_sheet('test')#在打开的excel中添加一个sheet
6、将数据写入excel
sheet.write(i,0,result[0])#写入excel,i行0列
sheet.write(i,1,result[1])
7、保存
writebook.save('answer.xls')#一定要记得保存
xlrd操作Excel表
对excel的操作
# todo 对excel的操作
import xlrd
# todo 打开excle
xl = xlrd.open_workbook(r'D:\file\data.xlsx')
#print(xl.read())
# todo 通过索引获取工作表
table = xl.sheets()[0]
print(table)
# 获取一共多少行
rows = table.nrows
print(rows)
# todo 获取第一行的内容,索引从0开始
row = table.row_values(0)
print(row)
# todo 获取第一列的整列的内容
col = table.col_values(0)
print(col)
# todo 获取单元格值,第几行第几个,索引从0开始
data = table.cell(3,0).value
print(data)
‘’‘写入excel文件’’’
'''写入excel文件'''
import xlsxwriter
# todo 创建excel文件
xl = xlsxwriter.Workbook(r'D:\testfile\test.xlsx')
# todo 添加sheet
sheet = xl.add_worksheet('sheet1')
# todo 往单元格cell添加数据,索引写入
sheet.write_string(0,0,'username')
# todo 位置写入
sheet.write_string('B1','password')
# todo 设置单元格宽度大小
sheet.set_column('A:B',30)
# todo 关闭文件
xl.close()
import xlrd
def config_data():
# 公共参数
xl = xlrd.open_workbook(r'D:\testfile\config.xlsx')
table = xl.sheets()[0]
# todo 获取单元行的内容,索引取值
row = table.row_values(0)
return row
'''测试data里面的配置数据是否可用'''
from App_automation.data import config_data
row = config_data()
print(row[0])