python操作excel用到3个模块,分别是xlrd,xlwt,xlutils;;;;xlrd用来读excel,xlwt用来写excel,xlutils用来修改excel 。
xlrd模块
import xlrd
book=xlrd.open_workbook('stu.xls')#打开excel文件
print(book.sheet_names())#获得所有sheet页的名称
sheet=book.sheet_by_index(0)#按顺序打开sheet页
# sheet=book.sheet_by_name('sheet1')#按sheet页的名称打开
print(sheet.cell(n,m).value)#取n行第m列的数据,需要加.value否则返回text:'value'
print(sheet.ncols)#获取列数
print(sheet.nrows)#获取行数
print(sheet.row_values(0))#获取某一行的数据。参数为第几行
print(sheet.col_values(0))#取某一列的数据
for i in range(sheet.nrows):#获取每行的数据
print(sheet.row_values(i))
xlwt模块
import xlwt
book = xlwt.Workbook() #新建一个excel
sheet = book.add_sheet('sheet1') #添加一个sheet页,参数为sheet页的名称
sheet.write(n,m,'姓名')#在第n行,第m列,写入内容'姓名'
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内保障每写完一行,又从下一行的第1列开始写起
for s in stu:
sheet.write(raw,col,s)
col+=1
raw+=1
book.save('kkk.xls')
xlutils模块
from xlutils.copy import copy
import xlrd
book1=xlrd.open_workbook('stu.xls')#利用xlrd模块打开excel
book2=copy(book1)#copy一份原来的excel
sheet=book2.get_sheet(0)#获得第几个sheet页
sheet.write(n,m,'string')#将第n行第m列内容替换成‘string’
book2.save('stu.xls')#保存excel