python 操作excel_1

操作excel安装的三种方式:

  1、pip install xlwt    #写excel

     pip install  xlrd    #读excel

       pip install  xlutils    #修改excel

  2、.whl

       pip install c:/user/niuhanyang/desktop/xxx.whl

  3、.tar.gz

    1、先解压

    2、解压之后在命令行里面进入到这个目录下

    3、执行python   setup.py install

  4、如果安装多个python版本

    python3.5 -m pip install XXX

    python2 -m pip install XXX

    python3.6 -m pip install XXX

一、写excel

 1 import xlwt
 2 import xlrd
 3 import xlutils
 4 
 5 # 写excel
 6 book=xlwt.Workbook()
 7 sheet=book.add_sheet('sheet1')
 8 # sheet.write(0,0,'id')  #指定行和列内容
 9 # sheet.write(0,1,'username')
10 # sheet.write(0,2,'password')
11 #
12 # sheet.write(1,0,'1')
13 # sheet.write(1,1,'niuhanyang')
14 # sheet.write(1,2,'123456')
15 
16 stus=[
17     [1,'njf','1234'],
18     [2,'njf1','1234'],
19     [3,'njf2','1234'],
20     [4,'njf3','1234'],
21     [5,'njf4','1234'],
22     [6,'njf5','1234'],
23     [7,'njf6','1234'],
24     [8,'njf7','1234'],
25     [9,'njf8','1234'],
26     [10,'njf9','1234'],
27 ]
28 line=0  #控制的是行
29 for stu in stus:
30     col=0
31     for s in stu:
32         sheet.write(line,col,s)
33         col+=1
34     line+=1
35 
36 book.save('stu.xls')

 

二、读excel

 1 import xlrd
 2 
 3 book=xlrd.open_workbook('stu.xls')
 4 sheet=book.sheet_by_index(0)  #根据sheet编号来
 5 # sheet=book.sheet_by_name('sheet1')   #根据 sheet名称来
 6 print(sheet.nrows)  #excel里面有多少行
 7 print(sheet.ncols)  #excel里面有多少列
 8 print(sheet.cell(0,0).value)  #获取第0行第0列的值
 9 print(sheet.row_values(0))  #获取到整行的内容
10 print(sheet.col_values(0)) #获取到整列的内容
11 
12 for i in range(sheet.nrows):  #循环获取每行的内容
13     print(sheet.row_values(i))

三、修改excel

 1 import xlrd
 2 import xlutils
 3 
 4 from xlutils import copy    #xlutils中导入copy
 5 
 6 book=xlrd.open_workbook('stu.xls')
 7 #先用xlrd打开一个excel
 8 new_book=copy.copy(book)
 9 #然后用xlutils里面的copy功能,复制一个excel
10 
11 sheet=new_book.get_sheet(0)  #获取sheet页
12 
13 sheet.write(0,1,'张三')  #修改第0行,第一列
14 sheet.write(1,1,'小军')   #修改第一行,第一列
15 new_book.save('stu.xls')

 

posted on 2018-10-16 23:08  jingshuhui  阅读(6960)  评论(2编辑  收藏  举报