標籤:開啟 row new 對象 pre xlrd values import xls
#讀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‘)
python操作excel