python--操作excal

操作excal

  读excal 需要安装xlrd模块,【pip install xlrd】安装即可

 1 import xlrd
 2 book=xlrd.open_workbook('stu.xls') #加载文件
 3 print(book.sheet_names())          #获取sheet页名字
 4 sheet=book.sheet_by_index(0)       #获取第0个sheet页
 5 sheet_name=book.sheet_by_name('stu1')    #获取sheet名字为stu的页
 6 print(sheet.nrows)                  #获取行数
 7 print(sheet.ncols)                  #获取列数
 8 print(sheet.row_values(0))          #获取第0行的所有值
 9 print(sheet.col_values(0))          #获取第0列的所有值
10 print(sheet.cell(0,0).value)        #获取第0行,第0列的单元格的值
11 
12 #读文件例子
13 sheet=book.sheet_by_index(0)
14 list=[]
15 for i in range(1,sheet.nrows):
16     d = {}
17     id = sheet.cell(i,0).value
18     name =sheet.cell(i,1).value
19     sex =sheet.cell(i,2).value
20     d['id']=int(id)
21     d['name']=name
22     d['sex']=sex
23     list.append(d)
24 print(list)

  写excal 需要安装xlwt模块,【pip install xlwt】安装即可

 1 import xlwt
 2 book=xlwt.Workbook()            #新建一个excal对象
 3 sheet=book.add_sheet('stu')     #添加名称为stu的sheet页
 4 sheet.write(0,0,'编号')         #插入单元格(0,0,'编号')
 5 book.save('stu_w.xls')            #保存excal文件,注意只能保存为xls格式
 6 
 7 #写文件例子
 8 import xlwt
 9 
10 title=['编号','姓名','性别']
11 lis =[{'sex': '', 'name': '小明', 'id': 1},
12       {'sex': '', 'name': '小黑', 'id': 2},
13       {'sex': '', 'name': '小怪', 'id': 3},
14       {'sex': '', 'name': '小白', 'id': 4}]
15 
16 book=xlwt.Workbook()
17 for i in range(len(title)):
18     sheet.write(0,i,title[i])
19 
20 for row in range(len(lis)):
21     id =lis[row]['id']
22     name =lis[row]['name']
23     sex =lis[row]['sex']
24     new_row=row+1
25     sheet.write(new_row,0,id)
26     sheet.write(new_row,1,name)
27     sheet.write(new_row,2,sex)
28 book.save('stu_w.xls')

  修改excal 需要安装xlutils模块,【pip install xlutils】安装即可。修改的原理就是复制出来一份进行修改。

1 import xlrd
2 from xlutils.copy import copy
3 book=xlrd.open_workbook('stu_w.xls')    #打开原来的excal
4 new_book=copy(book)                     #复制一个excal对象
5 sheet=new_book.get_sheet(0)             #获取sheet页
6 sheet.write(0,0,'haha')                 #更新值
7 new_book.save('new_stu_w.xls')          #另存为新文件

 

posted @ 2017-07-03 21:43  试尝百味  阅读(214)  评论(0编辑  收藏  举报