python操作excel

#读excel
import xlrd
book = xlrd.open_workbook(r'students.xlsx')
#打开excel
print(book.sheet_names())
#获取所有sheet的名字
sheet = book.sheet_by_index(0)
#根据sheet页的位置去取sheet
sheet2 = book.sheet_by_name('Sheet2')
#根据sheet页的名字获取sheet页
print(sheet.nrows)#获取sheet页里面的所有行数
print(sheet.ncols)#获取sheet页里面的所有列数
print(sheet.row_values(0))
#根据行号获取整行的数据
print(sheet.col_values(0))
#根据列获取整列的数据
print(sheet.cell(1,1).value)
#cell方法是获取指定单元格的数据,前面是行,后面是列
#读excel的时候,xls xlsx都可以读


#写excel

import xlwt
book = xlwt.Workbook()
#新建一个excel对象
sheet = book.add_sheet('stu')
#添加一个sheet页
sheet.write(0,0,'编号') #行的下标,列的下标,填写内容
book.save('stu.xls')
#写excel的时候,只能操作xls

#修改Excel,需要新copy一个excel对象
from xlutils.copy import copy
book = xlrd.open_workbook('new_stu.xls')
#打开原来的excel
new_book = copy(book)
#通过xlutils里面copy复制一个excel对象
sheet = new_book.get_sheet(0)
#获取sheet页
sheet.write(0,0,'id')
new_book.save('new_stu_1.xls')

posted @ 2017-07-08 16:24  喵咪的博客  阅读(233)  评论(0编辑  收藏  举报