使用Python讀寫/追加excel檔案
阿新 • • 發佈:2018-11-17
一:需要用到的庫
- xlrd:讀取excel檔案
- xlrd:寫入excel檔案
- xlutils:修改/追加excel檔案
直接pip install 庫名
即可安裝成功
二:官方文件
如果想詳細瞭解,請一定閱讀官方文件
- xlrd:http://xlrd.readthedocs.io/en/latest/
- xlwt:http://xlwt.readthedocs.io/en/latest/
- xlutils:http://xlutils.readthedocs.io/en/latest/index.html
三:xlrd讀取excel檔案
該demo讀取出所有單元格
from xlrd import open_workbook, cellname
book = open_workbook('odd.xls') # 開啟excel檔案
sheet = book.sheet_by_index(0) # 選取第一張表
print(sheet.name)
print(sheet.nrows)
print(sheet.ncols)
for row_index in range(sheet.nrows):
for col_index in range(sheet.ncols):
print(cellname(row_index, col_index), end='-') # 輸出單元格座標
print(sheet.cell(row_index, col_index).value) # 輸出單元格的值
四:xlwd寫入excel檔案
這個庫只能新建一個excel檔案
,將資料寫入其中,如果想要在已有的excel裡修改,需要用到xlutils庫
xlwt
建立一個Workbook
物件,使用它,最後呼叫sava
方法即可
sava
方法中傳入寫入的路徑的字串或檔案
如果你讀取的資料很大,row超過上千行,建議在每1000行的時候,使用flush_row_data()
方法,這樣會降低記憶體佔用
from tempfile import TemporaryFile
from xlwt import Workbook
book = Workbook() # 建立Workbook物件
sheet1 = book.add_sheet('Sheet 1') # 新增一張工作表
sheet1.write(0,0,'A1')
sheet1.write(0,1,'B1') # 在第0行,第1列,寫入資料B1
row1 = sheet1.row(1) # 第一行
row1.write(0,'A2')
row1.write(1,'B2') # 第1行,第1列,寫入資料B2
sheet1.col(0).width = 10000 # 設定第0列的寬度
book.save('simple.xls') # 儲存
五、追加excel檔案
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("simple2.xls") # 開啟需要追加的檔案
row = rb.sheet_by_index(0).nrows # 得到當前excel檔案行數
wb = copy(rb) # 將rb從xlrd物件轉變為xlwt物件
ws = wb.get_sheet(0) # 得到sheet
ws.write(row, 0, 'value') # 追加到最後一行
wb.save("simple2.xls") # 覆蓋原來的檔案