Python之操作excel

一、写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

猜你喜欢

转载自www.cnblogs.com/yz-test/p/9320630.html