码迷,mamicode.com
首页 > 其他好文 > 详细

操作excel

时间:2018-10-02 17:51:28      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:rom   utils   top   参数   index   imp   name   返回   dmi   

一、写excel

1、基本方法:如果写多行excle需要写很多行代码

 1 import xlwt  #写excel
 2 import xlrd  #读excel
 3 import xlutils #修改excel
 4 book = xlwt.Workbook()  #新建一个空白excle
 5 sheet = book.add_sheet(‘sheet‘) #加个sheet页
 6 sheet.write(0,0,‘id‘) #指定行和列写内容。第一行第一列
 7 sheet.write(0,1,‘username‘) #单元格写东西,第一行第二列
 8 sheet.write(0,2,‘password‘) #单元格写东西,第一行第一列
 9 
10 sheet.write(1,0,‘1‘) #第二行第一列
11 sheet.write(1,1,‘admin‘) #第二行第二列
12 sheet.write(1,2,‘123456‘) #第二行第三列
13 
14 book.save(‘stu.xls‘) #保存并命名,用.xls结尾,不要用.xlsx结尾,因为用word打不开

2、循环写excle

 1 import xlwt  #写excel
 2 import xlrd  #读excel
 3 import xlutils #修改excel
 4 book = xlwt.Workbook()  #新建一个空白excle
 5 sheet = book.add_sheet(‘sheet‘) #加个sheet页
 6 
 7 stus = [                     #二维数组
 8     [1,‘njf‘,‘1234‘],
 9     [2,‘xiaojun‘,‘1234‘],
10     [3,‘hailong‘,‘1234‘],
11     [5,‘xiaohei‘,‘1234‘],
12     [6,‘xiaohei‘,‘1234‘],
13     [7,‘xiaohei‘,‘1234‘],
14     [8,‘xiaohei‘,‘1234‘],
15     [9,‘xiaohei‘,‘1234‘],
16     [10,‘xiaohei‘,‘1234‘],
17 ]
18 row = 0 #控制行
19 for line in stus:
20     colum = 0  # 控制列
21     for s in line:
22         sheet.write(row,colum,s)
23         colum += 1
24     row += 1
25 book.save(‘stu.xls‘) #保存并命名,用.xls结尾

 二、读excel

#文件位置

ExcelFile=xlrd.open_workbook(r‘C:\Users\Administrator\Desktop\TestData.xlsx‘)

 1 import xlwt  #写excel
 2 import xlrd  #读excel
 3 import xlutils #修改excel
 4 book = xlrd.open_workbook(‘stu.xls‘)
 5 # book.sheet_by_name(‘sheet1‘)#根据sheet页的名字获取sheet页
 6 sheet = book.sheet_by_index(0) #根据编号获取sheet页 0代表第一个sheet页
 7 print(sheet.nrows)#excel里面有多少行
 8 print(sheet.ncols)#excel里面有多少列
 9 
10 print(sheet.cell(0,0).value) #获取指定单元格内容,第一行第一个列的值
11 print(sheet.cell(0,1).value) #获取指定单元格内容,第一行第二个列的值
12 
13 print(sheet.row_values(0)) #获取整行的内容,第一行,返回列表
14 print(sheet.col_values(0)) #获取整列的内容,第一列,返回列表

循环获取每行内容

1 for i in range(sheet.nrows): #循环获取每行的内容
2     print(sheet.row_values(i))

 三、修改excle

先复制excle,再写入复制的excle的sheet页,保存,修改完成

 1 import xlrd  #读excel
 2 # import xlutils #修改excel
 3 from xlutils import copy  #用这个
 4 book = xlrd.open_workbook(‘stu.xls‘) #先用xlrd打开一个excle
 5 new_book = copy.copy(book)#然后用xlutils里面的copy功能,复制一个excle
 6 
 7 sheet = new_book.get_sheet(0) #用这个方法获取sheet页,参数代表第几个sheet页
 8 sheet.write(0,1,‘AA‘)  #修改第一行第二列的值,就是写入复制的excle里
 9 sheet.write(1,1,‘BB‘)  #修改第二行第二列的值
10 new_book.save(‘stu.xls‘) #保存一下复制的excle,也就修改成功了

 

操作excel

标签:rom   utils   top   参数   index   imp   name   返回   dmi   

原文地址:https://www.cnblogs.com/once-again/p/9736198.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!