三個工具包
python操作excel的三個工具包如下,注意,只能操作.xls,不能操作.xlsx。
• xlrd: 對excel進行讀相關操作
• xlwt: 對excel進行寫相關操作
• xlutils: 對excel讀寫操作的整合
這三個工具包都可以直接使用pip進行下載:
sudo pip install xlrdsudo pip install xlwtsudo pip install xlutils1
xlwt的缺陷
xlwt只能創建一個全新的excel文件,然后對這個文件進行寫入內容以及保存。但是大多數情況下我們希望的是讀入一個excel文件,然后進行修改或追加,這個時候就需要xlutils了。
xlutils的簡單使用
下面的demo是給一個excel文件追加內容:
#coding:utf-8from xlrd import open_workbookfrom xlutils.copy import copyrexcel = open_workbook("collection.xls") # 用wlrd提供的方法讀取一個excel文件rows = rexcel.sheets()[0].nrows # 用wlrd提供的方法獲得現在已有的行數excel = copy(rexcel) # 用xlutils提供的copy方法將xlrd的對象轉化為xlwt的對象table = excel.get_sheet(0) # 用xlwt對象的方法獲得要操作的sheetvalues = ["1", "2", "3"]row = rowsfor value in values: table.write(row, 0, value) # xlwt對象的寫方法,參數分別是行、列、值 table.write(row, 1, "haha") table.write(row, 2, "lala") row += 1excel.save("collection.xls") # xlwt對象的保存方法,這時便覆蓋掉了原來的excel相關文檔
•xlrd:http://xlrd.readthedocs.io/en/latest/
•xlwt:http://xlwt.readthedocs.io/en/latest/
•xlutils:http://xlutils.readthedocs.io/en/latest/index.html
以上這篇Python讀寫/追加excel文件Demo分享就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答