Excel读取,修改,新建

一、读取Excel 

 1.打开excel表格

readbook = xlrd.open_workbook('D:\\automation--interface\\data\\testdata.xls')

 2.获取表格中所有sheet

sheets = readbook.sheet_names()         #返回所有sheet,<class 'list'>:['Sheet1', 'Sheet3', 'Sheet2']

 3.选择某个sheet

sheet = readbook.sheet_by_index(0)                 #按以索引方式选中,索引从0开始
sheet = readbook.sheet_by_name('Sheet1')           #按name的方式选中

 4.获取表格的 行 和 列

nrows = sheet.nrows           #返回行:3
ncols = sheet.ncols           #返回列:2

 5.获取表格具体内容

rows = sheet.row_values(1)          #返回第2行,<class 'list'>: ['小米', 5.0]
cols = sheet.col_values(1)          #返回第2列,<class 'list'>: ['年龄', 5.0, 7.0]
lng = sheet.cell(1,1).value         #返回坐标(1,1)的数据:5.0

 

二、xlwt 写入Excel

 1.打开excel并添加一个sheet

writebook = xlwt.Workbook()                #打开excel
test= writebook.add_sheet('test')          #添加一个名字叫test的sheet

 2.写入excel

test.write(0,1,'this is a test')           #第0行第1列写入字符串'this is a test'

 3.保存

writebook.save('testdata.xls')             #一定要保存为xls,后缀是xlsx的文件打不开

 

三、追加写入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import xlrd
 
from xlutils.copy import copy
 
向已存在Excel中添加sheet:
 
#打开需要操作的excel表
 
wb=xlrd.open_workbook(path)
 
#复制原有表
 
newb=copy(wb)
 
#新增sheet
 
wbsheet=newb.add_sheet(“sheet名”)
 
向已存在sheet中添加行
 
#获取原有excel表中名为‘table'的sheet
 
tabsheet = newb.get_sheet('table')
 
#k表示该sheet的最后一行
 
k=len(tabsheet.rows)
 
#在原有sheet后面新增数据
 
tabsheet.write(k,0,data1)

  

posted @   my_testing_road  阅读(271)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示