python简说(二十)操作excel

时间:2022-09-10 10:33:26

一.pip install xlrd
pip install xlwt
pip install xlutils

二.写excel

import xlwt
book = xlwt.Workbook() #新建一个excel
sheet = book.add_sheet('sheet1') #添加一个sheet页
row = 0 #行
for stu in stu_info:
#stu
col = 0 # 列
# [1, 'machunbo', 'sdfsd23sdfsdf2', '男', '北京'],
for s in stu: #控制列
sheet.write(row,col,s) #0 3 男
col+=1
row+=1
book.save('stu3.xls')
wps:xls,xlsx office:xls

二.读excel

import xlrd
book = xlrd.open_workbook('stu3.xls')
sheet = book.sheet_by_index(0)
# sheet = book.sheet_by_name('sheet1')
# print(sheet.cell(0,0).value)#获取指定单元格的内容
# print(sheet.row_values(0)) #获取整行的数据
# print(sheet.col_values(0))#获取整列的数据

print(sheet.nrows) #行数
print(sheet.ncols) #列数
for row in range(1,sheet.nrows):
print(sheet.row_values(row))

三.修改excel

import xlrd
from xlutils import copy

#1、先打开原来的excel
#2、复制一份
#3、在复制的excel上修改
#4、保存

book = xlrd.open_workbook('stu3.xls')
new_book = copy.copy(book) #
sheet = new_book.get_sheet(0) #修改excel的时候,得用get_sheet()
sheet.write(0,0,'id')
sheet.write(0,3,'password')
new_book.save('stu3.xls')