一, 写 excel
- import xlwt
- book=xlwt.Workbook() #创建 excel
- sheet=book.add_sheet('sheet1') #加一个 sheet
- sheet.write(0,0,'学生编号') #行, 列, 数据
- for index,line_data in enumerate(data): #使用枚举, 循环写数据到 excel
- for index2,col_data in enumerate(line_data):
- sheet.write(index,index2,col_data)
- book.save('1.xls') #保存的后缀得是 xls
二, 读 excel
- import xlrd
- book = xlrd.open_workbook('nhy.xls')
- book.nsheets #获取到 excel 里面总共有多少个 sheet 页
- sheet = book.sheet_by_index(0) #按 index 来找 sheet
- book.sheet_by_name('sheet1') #按 name 来找 sheet
- sheet.cell(0,0).value #指定行和列, 获取某个单元格里面的内容
- sheet.row_values(0) #获取某一行的数据
- sheet.nrows #这个就是 excel 里面总共有多少行
- sheet.col_values(0) #获取某一列的数据
- sheet.ncols #总共有多少列
三, 修改 excel
- import xlrd
- from xlutils import copy
- book1 = xlrd.open_workbook('nhy.xls') #打开原来的 excel
- new_book = copy.copy(book1) #拷贝一个新的 excel
- sheet = new_book.get_sheet(0) #获取第一个 sheet 页
- sheet.write(1,3,'王艳会') #改数据
- new_book.save('nhy.xls') #命名为原来的 excel
来源: http://www.bubuko.com/infodetail-2688068.html