day7 操作excel

参考文档:http://www.nnzhp.cn/archives/142
1、2、3 为写入excel
1、基础知识:
import xlwt
# 新建一个excel
book=xlwt.Workbook()
# 新建一个sheet
sheet=book.add_sheet('sheet1')
# 0,0代表行列
sheet.write(0,0,'姓名')
sheet.write(0,1,'性别')
sheet.write(0,2,'年龄')
# 不能用xlsx结尾的
book.save('stu.xls')


2、两个list ,,写入多行多列
import xlwt
book=xlwt.Workbook()
sheet=book.add_sheet('sheet1')
# sheet.write(0,0,'姓名')
# sheet.write(0,1,'性别')
# sheet.write(0,2,'年龄')
# sheet.write(0,3,'分数')
title=['姓名','年龄','性别','分数']
stus=[['m','20','女','89'],
['m1', '20', '女','89'],
['m2', '20', '女', '89']
]
cols=0
for t in title:
sheet.write(0, cols, t)
cols+=1
#定义行
row=1
# 定义列
new_col=0
# 写每一行的
for s in stus:
# 写每一列
for i in s:
sheet.write(row, new_col, i)
new_col+=1
row+=1
new_col = 0
book.save('stu1.xls')

3、一个list 循环写入
import xlwt
book=xlwt.Workbook()
sheet=book.add_sheet('sheet1')

stus=[['姓名','年龄','性别','分数'],
['m','20','女','89'],
['m1', '20', '女','89'],
['m2', '20', '女', '89']
]
# 行
row=0
for s in stus:
# 列
col = 0
for i in s:
sheet.write(row, col, i)
# 小循环加1,循环列的数据
col += 1
# 大循环加1,循环行的数据
row += 1
book.save('stu1.xls')
以下为读取excel
import xlrd
book=xlrd.open_workbook('stu1.xls')
# 根据顺序获取sheet
sheet=book.sheet_by_index(0)
# 根据名字获取
# sheet=book.sheet_by_name('')
# .value直接获取到值
# print(sheet.cell(0,0).value)
# print(sheet.cell(0,1).value)
# print(sheet.cell(0,2).value)
# print(sheet.cell(0,3).value)
# 获取excel里面有多少列
print(sheet.ncols)
# 获取excel里面有多少行
print(sheet.nrows)
# 获取到所有行
for i in range(sheet.nrows):
# 第几行的数据
print(sheet.row_values(i))
# 第几列的数据,以0开始
print(sheet.col_values(2))


 
以下为修改excel
from xlutils.copy import copy
import xlrd
# 先打开
book1=xlrd.open_workbook('stu1.xls')
# 先拷贝一份,再去修改这一份
book2=copy(book1)
# 获取第几个sheet
sheet=book2.get_sheet(0)

sheet.write(1,3,99)
sheet.write(2,0,'http:www.baidu.com')
book2.save('stu1.xls')


作业1.从数据库导出信息,放到excel里面
作业2:提供一个excel ,然后把excel中的数据中的数据,调用添加学生信息的接口,
doc.nnzhp.cn





猜你喜欢

转载自www.cnblogs.com/sheery/p/8921462.html