python--操作excal

來源:互聯網
上載者:User

標籤:小白   姓名   載入   插入   cal   操作   install   add   檔案   

操作excal

  讀excal 需要安裝xlrd模組,【pip install xlrd】安裝即可

 1 import xlrd 2 book=xlrd.open_workbook(‘stu.xls‘) #負載檔案 3 print(book.sheet_names())          #擷取sheet頁名字 4 sheet=book.sheet_by_index(0)       #擷取第0個sheet頁 5 sheet_name=book.sheet_by_name(‘stu1‘)    #擷取sheet名字為stu的頁 6 print(sheet.nrows)                  #擷取行數 7 print(sheet.ncols)                  #擷取列數 8 print(sheet.row_values(0))          #擷取第0行的所有值 9 print(sheet.col_values(0))          #擷取第0列的所有值10 print(sheet.cell(0,0).value)        #擷取第0行,第0列的儲存格的值11 12 #讀檔案例子13 sheet=book.sheet_by_index(0)14 list=[]15 for i in range(1,sheet.nrows):16     d = {}17     id = sheet.cell(i,0).value18     name =sheet.cell(i,1).value19     sex =sheet.cell(i,2).value20     d[‘id‘]=int(id)21     d[‘name‘]=name22     d[‘sex‘]=sex23     list.append(d)24 print(list)

  寫excal 需要安裝xlwt模組,【pip install xlwt】安裝即可

 1 import xlwt 2 book=xlwt.Workbook()            #建立一個excal對象 3 sheet=book.add_sheet(‘stu‘)     #添加名稱為stu的sheet頁 4 sheet.write(0,0,‘編號‘)         #插入儲存格(0,0,‘編號‘) 5 book.save(‘stu_w.xls‘)            #儲存excal檔案,注意只能儲存為xls格式 6  7 #寫檔案例子 8 import xlwt 9 10 title=[‘編號‘,‘姓名‘,‘性別‘]11 lis =[{‘sex‘: ‘女‘, ‘name‘: ‘小明‘, ‘id‘: 1},12       {‘sex‘: ‘男‘, ‘name‘: ‘小黑‘, ‘id‘: 2},13       {‘sex‘: ‘男‘, ‘name‘: ‘小怪‘, ‘id‘: 3},14       {‘sex‘: ‘女‘, ‘name‘: ‘小白‘, ‘id‘: 4}]15 16 book=xlwt.Workbook()17 for i in range(len(title)):18     sheet.write(0,i,title[i])19 20 for row in range(len(lis)):21     id =lis[row][‘id‘]22     name =lis[row][‘name‘]23     sex =lis[row][‘sex‘]24     new_row=row+125     sheet.write(new_row,0,id)26     sheet.write(new_row,1,name)27     sheet.write(new_row,2,sex)28 book.save(‘stu_w.xls‘)

  修改excal 需要安裝xlutils模組,【pip install xlutils】安裝即可。修改的原理就是複製出來一份進行修改。

1 import xlrd2 from xlutils.copy import copy3 book=xlrd.open_workbook(‘stu_w.xls‘)    #開啟原來的excal4 new_book=copy(book)                     #複製一個excal對象5 sheet=new_book.get_sheet(0)             #擷取sheet頁6 sheet.write(0,0,‘haha‘)                 #更新值7 new_book.save(‘new_stu_w.xls‘)          #另存新檔新檔案

 

python--操作excal

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.