python操作excel

來源:互聯網
上載者:User

標籤:開啟   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.