Python學習筆記-操作excel

來源:互聯網
上載者:User

標籤:values   strong   index   rom   +=   xls   寫入   使用   操作   

python操作excel:使用pip安裝即可

一、xlwt:寫excel

import xlwtbook = xlwt.Workbook()             #建立一個excelsheet = book.add_sheet(‘sheet1‘)   #加sheet頁sheet.write(0,0,‘姓名‘)             #行、列、寫入的內容sheet.write(0,1,‘年齡‘)sheet.write(0,2,‘性別‘)book.save(‘stu.xls‘)               #結尾一定要用.xls
  import xlwt        title = [‘姓名‘,‘年齡‘,‘性別‘,‘分數‘]        stus = [[‘mary‘,20,‘女‘,89.9],[‘mary‘,20,‘女‘,89.9],[‘mary‘,20,‘女‘,89.9],[‘mary‘,20,‘女‘,89.9]]        #建立一個excel對象        wbk = xlwt.Workbook()        #添加一個名為 課程表的sheet頁        sheet = wbk.add_sheet(‘stu‘)        for i in  range(len(title)):#寫入表頭            sheet.write(0,i,title[i])#寫入每行,第一個值是行,第二個值是列,第三個是寫入的值        row = 1 #行        for i in stus:            col = 0#列            for j in i:                sheet.write(row,col,j)#迴圈寫入每行資料                col+=1            row+=1        #儲存資料到‘test.xls’檔案中        wbk.save(‘szz.xls‘)#儲存excel必須使用尾碼名是.xls的,不是能是.xlsx的

 

二、xlrd:讀excel

import xlrdbook = xlrd.open_workbook(‘app_student.xls‘)   #開啟的這個excel必須存在,否則會報錯sheet = book.sheet_by_index(0)        #根據sheet頁的索引擷取sheet頁sheet2 = book.sheet_by_name(‘shee1‘)    #根據sheet頁的名字擷取sheet頁print(sheet.cell(0,0).value) print(sheet.cell(1,0).value)   #擷取指定儲存格的值,第一個值是列,第二個值是行print(sheet.row_values(0))     #擷取到第幾行的內容print(sheet.row_values(1))     #擷取到第幾行的內容print(sheet.nrows)          #擷取到excel裡面總共有多少行for i in range(sheet.nrows):    #迴圈擷取到每行資料    print(sheet.row_values(i))  #取每行的資料print(sheet.ncols)         #總共多少列print(sheet.col_values(0))    #取第幾列的資料

 

三、xlutils:修改excel

xlutils模組用來修改excel的內容,不能直接修改原來的excel內容,必須得先複製一個新的excel,然後對這個新的excel進行修改,用法如下:

import xlrdfrom xlutils import copy        #匯入xlutils模組的複製excel模組book = xlrd.open_workbook(‘app_student.xls‘) #先用xlrd模組,開啟一個excelnew_book = copy.copy(book)     #通過xlutils這個模組裡面copy方法,複製一份excelsheet = new_book.get_sheet(0)   #擷取sheet頁lis = [‘編號‘,‘名字‘,‘性別‘,‘年齡‘,‘地址‘,‘班級‘,‘手機號‘,‘金幣‘]for col,filed in enumerate(lis):    sheet.write(0,col,filed)    #寫入excel,第一個值是行,第二個值是列new_book.save(‘app_student.xls‘) #儲存新的excel,儲存excel必須使用尾碼名是.xls的,不是能是.xlsx的

 

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.