關於Python excel寫、讀和追加
阿新 • • 發佈:2018-12-14
- 關於Python excel寫入
在Python中,匯入以下三個模組,對excel表格讀、寫、追加資料:
1.
wlrd
讀取excel表中的資料。 2.xlwt
建立一個全新的excel檔案,然後對這個檔案進行寫入內容以及儲存。 3.xlutils
讀入一個excel檔案,然後進行修改或追加,不能操作xlsx
,只能操作xls
。
import xlwt text = ['a','b','c','d','e'] #建立workbook workbook = xlwt.Workbook(encoding='utf-8', style_compression=0) sheet = workbook.add_sheet('test', cell_overwrite_ok=True) col = 0 for row in range(int(len(text))): # 將text內容寫入excel的[rpw,col] sheet.write(row, col, text[row]) workbook.save('test.xls')
結果
- 關於Python excel讀取
import xlrd data = xlrd.open_workbook('test.xls') #通過索引獲取 table1 = data.sheets()[0] table2 = data.sheet_by_index(0) #通過名稱獲取 table3=data.sheet_by_name('test') #獲取行和列 nrows = table1.nrows ncols = table1.ncols rows = table1.row_values(0) cols = table1.col_values(0) item = table1.cell_value(0,0) item1 = table1.cell_value(2,0) print(item, item1)
結果
- 關於Python excel追加資料
import xlrd
import xlutils.copy
data = xlrd.open_workbook('test.xls')
ws = xlutils.copy.copy(data)
table=ws.get_sheet(0)
table.write(0,5,'append')
ws.save('test.xls')
結果