写extel
import xlwt
book = xlwt.Workbook()#新建一个extel
sheet = book.add_sheet('students') #新建一个sheet1
#
sheet.write(0,0,'id')#0行0列
sheet.write(0,1,'name')
sheet.write(0,2,'age')
#
sheet.write(1,0,'1')
sheet.write(1,1,'xiaohei')
sheet.write(1,2,'38')
#
book.save('students.xls') #如果后缀写成xlsx,使用微软的office打不开
使用extel写一个list二维数组
import xlwt
stus = [
[1,'ds','bejing',51],
[2,'fd','shanghai',28],
[3,'zc','shanghai',16],
[4,'lhy','shanghai',21],
[5,'ylm','shanghai',35],
[6,'wxl','beijing',16],
]
stus.insert(0,['编号','姓名','地址','年龄'])
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
row = 0
for stu in stus:#控制行
col=0#列号这是while循环
for s in stu:#控制列
sheet.write(row,col,s)
col+=1
row+=1#行号在变
book.save('students.xls')
简单的写法,写行和列 使用枚举方法
l=['a','b','c','d']
for i in enumerate(l):
print(i) 枚举会吧List转成元祖 0,a
for row,stu in enumerate(stus):#控制行 0 1 2 3 4 5
for row,stu in enumerate(stus,1):#控制行 0 1 2 3 4 5 默认从1开始
for col,s in enumerate(stu):#控制列
sheet.write(row,col,s)
import xlwt
stus = [
[1,'ds','bejing',51],
[2,'fd','shanghai',28],
[3,'zc','shanghai',16],
[4,'lhy','shanghai',21],
[5,'ylm','shanghai',35],
[6,'wxl','beijing',16],
]
stus.insert(0,['编号','姓名','地址','年龄'])
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
for row,stu in enumerate(stus):#控制行 0 1 2 3 4 5 row 是行号.stu是内容
for col,s in enumerate(stu):#控制列 col就是行号 s内容
sheet.write(row,col,s)
book.save('students.xls')
extel读的操作
import xlrd
book = xlrd.open_workbook('students.xls')
# sheet = book.sheet_by_index(0)
sheet = book.sheet_by_name('sheet1')
# print(book.sheets())#所有的sheet页,返回的是一个list,list里面就是每个sheet对象
for s in book.sheets():#
print(s.row_values(2))#第二行
print(sheet.cell(0,0).value)#0行0列
print(sheet.row_values(0)) #第一行
print(sheet.row_values(1))#第二行
print(sheet.col_values(0)) #第一列
print(sheet.col_values(1)) #第二列
print(sheet.nrows)#多少行
print(sheet.ncols)#多少列
extel 修改
from xlutils import copy #复制一个新的修改
import xlrd
book = xlrd.open_workbook('students.xls')
sheet = book.sheet_by_index(0)
new_book = copy.copy(book)#复制一份新的
copy_sheet = new_book.get_sheet(0)#获取sheet页方法
#1,7 #1 2 3 4 5 6
for row in range(1,sheet.nrows-1):#1 2 3 4 5 6 7 循环行从第一行开始因为0行是表头,减1就是去掉一行
addr = sheet.cell(row,2).value#行号
print()
addr = addr.replace('beijing',"北京").replace('shanghai','上海')
copy_sheet.write(row,2,addr)
new_book.save('students.xls')