Python之操作Excel

时间:2023-03-08 18:55:25
Python之操作Excel

使用之前先导入三个模块:

import xlwt  #只能写Excel
import xlrd #只能读Excel
import xlutils #修改Excel,在原来的基础上修改

一、写EXCEL

book=xlwt.Workbook()  #新建一个Excel
sheet=book.add_sheet('sheet1')#建一个sheet页
sheet.write(0,0,'id')#指定行和列,写内容
sheet.write(0,1,'username')
sheet.write(0,2,'password') sheet.write(1,0,'')
sheet.write(1,1,'xiaoming')
sheet.write(1,2,'') book.save('stu.xls')#保存内容
#注意:要保存成结尾时.xls的文件,.xlsx用微软的文件打不开,只能用WPS的打开

使用循环方式写入内容:

#给定文件内容:
stus=[
[1,'njf',''],
[2,'xiaojun',''],
[3,'hailong',''],
[4,'xiaohei',''],
[5,'xiaohei',''],
[6,'xiaohei',''],
[7,'xiaohei',''],
[8,'xiaohei',''],
[9,'xiaohei',''],
] #内容写入Excel
book=xlrt.Workbook() #新建一个Excel
sheet=book.add_sheet('sheet1') #新建一个sheet页 line=0 #控制的是行
for stu in stus:
col=0 #控制列
for s in stu:
sheet.write(line,col,s)
col+=1
line+=1 book.save('stu.xls') #保存内容

二、读EXCEL

import xlrd

book=xlrd.open_workbook('stu.xls') #打开Excel
sheet=book.sheet_by_index(0) #根据编号获取sheet页
#sheet=book.sheet_by_name('sheet1') #也可以根据sheet页名字获取sheet页 print(sheet.nrows) #Excel里有多少行
print(sheet.ncols) #Excel里有多少列 print(sheet.cell(0,0).value) #获取到指定单元格的内容
print(sheet.cell(0,1).value) #获取到指定单元格的内容 print(sheet.row_values(0)) #获取到整行的内容
print(sheet.col_values(0)) #获取到整列的内容 for i in range(sheet.nrows): #循环获取每行的内容
print(sheet.row_values(i))

三、修改EXCEL

由于xlwt模块只能写一次,再重新打开Excel后会覆盖原来的内容;而xlrd模块只能读,因此修改Excel就要使用xlutils模块了。

#import xlutils
import xlrd #两个模块配合使用
from xlutils import copy book=xlrd.open_workbook('stu.xls')
#先用xlrd打开一个Excel
new_book=copy.copy(book)
#然后用xlutils里面的copy功能,复制一个Excel sheet=new_book.get_sheet(0) #获取sheet页,注意这里的sheet页是xlutils里的,只能用.get_sheet()的方法获取了 sheet.write(0,1,'小明') new_book.save('stu.xls') #修改完内容后再保存成同名的Excel