Python操作excel

178 阅读2分钟
操作excel安装的三种方式:
  1、pip instaill xlwt #写excel
    pip instaill xlrd #读excel
   pip instaill xlutils #修改excel
  2、.whl
   pip instail c:/user/niuhanyang/desktop/xxx.whl
  3、.tar.gz
    1、先解压
    2、解压之后在命令行里面进入到这个目录下
    3、执行python setup.py install
  4、如果安装多个python版本
    python3.5 -m pip instaill XXX
    python2 -m pip instail XXX
    python3.6 -m pip instail XXX
一、写excel
[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import xlwt
import xlrd
import xlutils
# 写excel
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
# sheet.write(0,0,'id') #指定行和列内容
# sheet.write(0,1,'username')
# sheet.write(0,2,'password')
#
# sheet.write(1,0,'1')
# sheet.write(1,1,'niuhanyang')
# sheet.write(1,2,'123456')
stus = [
[1, 'njf', '1234'],
[2, 'njf1', '1234'],
[3, 'njf2', '1234'],
[4, 'njf3', '1234'],
[5, 'njf4', '1234'],
[6, 'njf5', '1234'],
[7, 'njf6', '1234'],
[8, 'njf7', '1234'],
[9, 'njf8', '1234'],
[10, 'njf9', '1234'],
]
line = 0 # 控制的是行
for stu in stus:
col = 0
for s in stu:
sheet.write(line, col, s)
col += 1
line += 1
book.save('stu.xls')
二、读excel
[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
import xlrd
book = xlrd.open_workbook('stu.xls')
sheet = book.sheet_by_index(0) # 根据sheet编号来
# sheet=book.sheet_by_name('sheet1') #根据 sheet名称来
print(sheet.nrows) # excel里面有多少行
print(sheet.ncols) # excel里面有多少列
print(sheet.cell(0, 0).value) # 获取第0行第0列的值
print(sheet.row_values(0)) # 获取到整行的内容
print(sheet.col_values(0)) # 获取到整列的内容
for i in range(sheet.nrows): # 循环获取每行的内容
print(sheet.row_values(i))

三、修改excel
[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
import xlrd
import xlutils
from xlutils import copy # xlutils中导入copy
book = xlrd.open_workbook('stu.xls')
# 先用xlrd打开一个excel
new_book = copy.copy(book)
# 然后用xlutils里面的copy功能,复制一个excel
sheet = new_book.get_sheet(0) # 获取sheet页
sheet.write(0, 1, '张三') # 修改第0行,第一列
sheet.write(1, 1, '小军') # 修改第一行,第一列
new_book.save('stu.xls')

更多技术资讯可关注:itheimaGZ获取