python学习笔记(十三)-python对Excel进行读写修改操作

时间:2025-02-15 10:35:02

日常工作中会遇到Excel的读写问题。我们可以使用xlwt 模块将数据写入Excel表格,使用xlrd 模块从Excel读取数据,使用xlutils模块和xlrd模块结合对Excel数据进行修改。下面介绍如何实现使用python对Excel进行读写修改操作。

1、对Excel的写操作:

import xlwt

book = xlwt.Workbook() #新建一个excel

sheet = book.add_sheet('sheet1') #添加一个sheet页

sheet.write(0,0,'姓名') #Excel第一行第一列写入姓名

sheet.write(0,1,'性别') #Excel第一行第二列写入性别

sheet.write(0,2,'年龄') #Excel第一行第三列写入年龄

book.save('stu.xls') #微软的office不能用xlsx结尾的,wps随意

举例:从二维列表中读取数据,写入到excel中。

stus = [

['姓名','年龄','性别','分数'],

['mary', 20, '女', 89.9],

['mary', 20, '女', 89.9],

['mary', 20, '女', 89.9],

['mary', 20, '女', 89.9]]

book = xlwt.Workbook() #新建一个excel

sheet = book.add_sheet('sheet1') #添加一个sheet页

raw = 0#控制行的

for stu in stus:

col = 0 #控制列

for s in stu:

sheet.write(raw,col,s)

col+=1

raw+=1

book.save('kkk.xls')

2、对Excel的读操作

import xlrd

book = xlrd.open_workbook('stu.xls') #打开一个excel

sheet = book.sheet_by_index(0) #根据顺序获取sheet

sheet2 = book.sheet_by_name('sheet1') #根据sheet页名字获取sheet

print(sheet.cell(0,0).value) #指定行和列获取数据

print(sheet.ncols) #获取excel里面有多少列

print(sheet.nrows) #获取excel里面有多少行

sheet.row_values(1)#取第几行的数据

print(sheet.col_values(1)) #取第几列的数据

for i in range(sheet.nrows): # 0 1 2 3 4 5

print(sheet.row_values(i)) #取第几行的数据

3、对Excel修改操作

from xlutils.copy import copy #从xlutils模块导入copy

import xlrd

book1 = xlrd.open_workbook('stu.xls') #得到Excel文件的book对象,实例化对象

book2 = copy(book1) #拷贝一份原来的excel

sheet = book2.get_sheet(0) #获取第几个sheet页

sheet.write(1,3,0) #对拷贝的excel第2行,第4列数据为0

sheet.write(1,0,'小黑') #对拷贝的excel第2行,第1列数据为小黑

book2.save('stu.xls') #保存修改后excel