python 處理Excel 常見問題- 寫入Excel
阿新 • • 發佈:2019-01-02
情境:讀取Excel自動處理時,往往會在資料後面加一個處理標識,記錄以處理資料與未處理資料
Excel結果如下:import xlrd import xlwt def read_excel(fname,sheetname): book = xlrd.open_workbook(fname) sheet = book.sheet_by_name(sheetname) # 獲取行數 nrows = sheet.nrows row_list = [] # 獲取各行資料 for i in range(1, nrows): row_data = sheet.row_values(i) row_list.append(row_data) return row_list def write_excel(datas,filename): book = xlwt.Workbook() sheet1 = book.add_sheet('Sheet1') for x,data in enumerate(datas): print(data) for y,param in enumerate(data): if y == 2: sheet1.write(x,y,'True') else: sheet1.write(x,y,param) book.save(filename) print(read_excel('demo.xls','Sheet1')) datas = read_excel('demo.xls','Sheet1')
仔細的朋友可能發現了,新Excel中,各欄位的標題沒有了,至於原因,在“注意”中已經說明 當我們需要對以存在的Excel進行寫入而不是重新建立時,需要使用xlutils進行 2.xlutils
from xlutils.copy import copy def write_exist_excel(filename,sheetname): #讀取舊Excel中的資訊 exist_excel = xlrd.open_workbook(filename) sheet = exist_excel.sheet_by_name(sheetname) nrows = sheet.nrows #複製已存在的Excel new_excel = copy(exist_excel) new_sheet = new_excel.get_sheet(sheetname) for i in range(1,nrows): row_data = sheet.row_values(i) print(row_data) # 在新的Excel中寫入 new_sheet.write(i,2,'True') new_excel.save(filename) write_exist_excel('demo.xls','Sheet1')