python操作excel(xlwt写,xlrd读)基本方法

python操作excle在测试工作中还是很有用的,比如读取测试数据,回写测试结果到excel。

1、安装

pip install xlwt

pip install xlrd

2、写excel

# 导入模块,xlwt是写,xlrd是读
import xlw # 创建excel文件(打开一个对象)
xls = xlwt.Workbook()
# 创建sheet,sheet名称为sample
sheet = xls.add_sheet('sample')
# 写入4行2列数据
for j in range(1,5):
for i in range(1,3):
sheet.write(j, i, 'test[{}][{}]'.format(j,i))
# 在第8行5列写入数据
sheet.write(7, 5, 'hello python')
# 保存excel,文件名称为sample.xls
xls.save('sample.xls')

生成的excel:

python操作excel(xlwt写,xlrd读)基本方法

3、读excel

import xlrd
# 打开excel
xls = xlrd.open_workbook('sample.xls')
print(xls) # <xlrd.book.Book object at 0x0000000002A5D1D0>
# 通过索引或者名称获取sheet
# sheet = xls.sheets()[0]
# sheet = xls.sheet_by_index(0)
# sheet = xls.sheet_by_name(u'工作表1')
sheet = xls.sheet_by_name('sample')
print(sheet) # <xlrd.sheet.Sheet object at 0x0000000002A80668> # 单元格
cell_B2 = sheet.cell(1,1).value
print(cell_B2) # test[1][1] # 行索引
cell_B3 = sheet.row(2)[1].value
print(cell_B3) # test[2][1]
# 列索引
cell_C2 = sheet.col(2)[1].value
print(cell_C2) # test[1][2] # 获取整行的值,返回一个列表
row_values = sheet.row_values(0) # 第0行
print(row_values) # ['', '', '', '', '', '']
# 获取整列的值,返回一个列表
col_values = sheet.col_values(1) # 第1列
print(col_values) # ['', 'test[1][1]', 'test[2][1]', 'test[3][1]', 'test[4][1]', '', '', ''] # 获取行数和列数,行数和列数都是从第0行和0列开始,哪怕0行或0列没数据
nrows = sheet.nrows
ncols = sheet.ncols
print('行:'+str(nrows), '列:'+str(ncols)) # 行:8 列:6 # 循环输出行数据
print('行数据'.center(10,'*'))
for i in range(nrows):
print(sheet.row_values(i)) # 总共8行数据 # 循环输出列数据
print('列数据'.center(10,'*'))
for i in range(ncols):
print(sheet.col_values(i)) # 总共6列数据

程序输出:

python操作excel(xlwt写,xlrd读)基本方法

整理自网络,如有侵权,请联系删除。  

上一篇:使用 JavaScript File API 实现文件上传


下一篇:Python操作Excel