python可以对excel进行写的操作,读的操作和修改的操作,做不同的功能需要导入不同的模块
1、对 excel进行写的操作
import xlwt
book=xlwt.Workbook() #新建一个excel
sheet=book.add_sheet('sheet1') #添加一个sheet
stu_info = [
['编号','姓名','密码','性别','地址'],
[1,'machunbo','sdfsd23sdfsdf2','男','北京'],
[2,'machunbo2','sdfsd23sdfsdf2','男','北京'],
[3,'machunb3','sdfsd23sdfsdf2','男','北京'],
[4,'machunbo4','sdfsd23sdfsdf2','男','北京'],
[5,'machunbo5','sdfsd23sdfsdf2','男','北京'],
[6,'machunbo6','sdfsd23sdfsdf2','男','北京'],
]
#第一种方式写入到excel中
row=0
for stu in stu_info:
col=0
for s in stu:
sheet.write(row,col,s)
col+=1
row+=1
book.save('stu.xls') #wps 用xls,xlsx 微软的用xls
#第二种方式enumerate同时取到下标和值
for index ,value in enumerate(stu_info):
for index1,v2 in enumerate(value):
sheet.write(index,index1,v2)
book.save('stu.xls') #wps 用xls,xlsx 微软的用xls
2、对excel进行读取的操作
import xlrd
book=xlrd.open_workboo(‘stu.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(sheet.nrows):
print(sheet.row_values(row))
3、修改excel
import xlrd
from xlutils import copy
book=xlrd.open_workbook(‘stu.xls’)
new_book=copy.copy(book) #复制 excel
sheet=new_book.get_sheet(0)#修改时,只能用get_sheet方法
sheet.write(0,0,'id')
new_book.save('stu.xls')