from xlutils import copy #修改excel
import xlrd #修改excel同时需要xlrd第三方模块
book = xlrd.open_workbook('students.xls')# 1.打开原excel
sheet = book.sheet_by_index(0)# 2.读取excel,xlrd的方法,获取第0个sheet页,复制excel(xlutils) 里不能通过book.sheet_by_index获取某个sheet页的内容
new_book = copy.copy(book)# 3.复制一个新的excel,在新的excel上做修改
copy_sheet = new_book.get_sheet(0)# 4.获取复制后的excel的第0个sheet页;复制excel(xlutils) 里通过book.sheet_by_index获取某个sheet页的内容
for row in range(1,sheet.nrows-1):# 5.获取要改的某行或某列的值;sheet.nrows,sheet共有多少行
addr = sheet.cell(row,2).value # 5.获取要改的某行或某列的值;sheet.cell(row,2).value,sheet第row行第2列数据
addr = addr.replace('beijing',"北京").replace('shanghai','上海')# 6.在复制后的excel上更改原值;把'beijing'替换为’北京‘,把'shanghai'替换为’上海‘
copy_sheet.write(row,2,addr) # 7.把更改的值写入复制后的excel的sheet页中;把copy_sheet的第row行第2列值都改为addr
new_book.save('students.xls')# 8.复制的excel以原excel文件名命名保存
excel操作--更改excel
最新推荐文章于 2023-02-26 12:32:11 发布