python:操作excel

來源:互聯網
上載者:User

標籤:write   app   excel   i+1   xlsx   讀取   xlwt   list   []   

需要pip安裝xlrd,xlwt,xlutils模組,分別是讀取excel,寫入excel,修改excel的

xlrd模組:
import xlrd
book=xlrd.open_workbook(r‘students.xlsx‘) #開啟一個Excel檔案;括弧裡檔案不指定絕對路徑的話,就是指目前的目錄下的excel檔案
print(book.sheet_names()) #擷取所有sheet的名字
sheet=book.sheet_by_index(0) #根據sheet頁的第幾個位置去取sheet
sheet=book.sheet_by_name(‘sheet2‘) #根據sheet頁的名字擷取sheet頁
print(sheet.nrows) #擷取該指定sheet頁的所有行數,擷取的是數字
print(sheet.ncols) #擷取該指定sheet頁的所有列數,擷取的是數字
print(sheet.row_values(0)) #根據行號擷取整行的資料,擷取出來的是list
print(sheet.col_values(0)) #根據列號擷取整列的資料,擷取出來的是list
print(sheet.cell(2,1).value) #擷取第3行第2列儲存格裡的內容;加上value擷取出來的是字串類型

eg1:讀表格,並把讀出的資料放在列表裡,列表裡的元素是字典,字典裡key是id,name,sex
import xlrd
book=xlrd.open_workbook(r‘students.xlsx‘)
sheet=book.sheet_by_index(0) #開啟第一個sheet表
n=sheet.nrows #求該sheet表中所有的行數
all_list=[] #定義一個空列表,放取出來的資料
for i in range(1,n): #按表格裡所有的行數迴圈
dic = {}
lis=sheet.row_values(i)
dic[‘id‘]=lis[0]
dic[‘name‘]=lis[1]
dic[‘sex‘]=lis[2]
all_list.append(dic)
print(all_list)

xlwt模組
import xlwt
book=xlwt.Workbook() #建立一個excel對象
sheet=book.add_sheet(‘student‘) #增加一個sheet頁,命名為student
sheet.write(0,0,‘編號‘) #給第一行第一列的儲存格寫上“編號”
book.save(‘stu.xls‘) #儲存,檔案名稱儲存為stu.xls。儲存在目前的目錄下(或者寫絕對路徑)
#PS:讀excel的時候,xls xlsx的都可以讀;但寫excel的時候,儲存的檔案名稱必須是xls

eg2:給出lis和title,寫一個表格
import xlwt
lis=[{‘姓名‘: ‘小名‘, ‘性別‘: ‘女‘, ‘id‘: 1.0}, {‘姓名‘: ‘小李‘, ‘性別‘: ‘中‘, ‘id‘: 2.0}, {‘姓名‘: ‘小王‘, ‘性別‘: ‘男‘, ‘id‘: 3.0},
{‘姓名‘: ‘校長‘, ‘性別‘: ‘女‘, ‘id‘: 4.0}]
title=[‘編號‘,‘姓名‘,‘性別‘]
book=xlwt.Workbook()
sheet=book.add_sheet(‘test‘)
for i in range(len(title)): #迴圈列表的長度
sheet.write(0,i,title[i]) #寫表頭
for i in range(len(lis)):
sheet.write(i+1,0,lis[i][‘id‘])
sheet.write(i+1,1,lis[i][‘姓名‘])
sheet.write(i+1,2,lis[i][‘性別‘]) #寫每一個元素
book.save(‘test.xls‘)

xlutils模組
import xlrd,xlutils
from xlutils.copy import copy #引用xlutils模組裡的copy
book=xlrd.open_workbook(r‘stu.xls‘) #開啟原來的excel
new_book=copy(book) #通過xlutils裡面的copy複製一個excel對象
sheet=new_book.get_sheet(0) #擷取第一個sheet頁;拷貝的新對象沒有sheet_by_index()方法,只有get_sheet()方法
sheet.write(0,0,‘id‘) #把第一行第一列的儲存格修改掉
new_book.save(‘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.