文的文字及圖片來源於網絡,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。
作者: Rhinoceros
PS:如有需要Python學習資料的小伙伴可以加點擊下方鏈接自行獲取
http://note.youdao.com/noteshare?id=3054cce4add8a909e784ad934f956cef
單個excel文件
1 # 使用xlrd讀取excel文件 2 wb = open_workbook(path + '/' + name)
獲取每個工作表
1 # 獲取當前文件的工作表(sheet)list 2 sheetList = wb.sheets() 3 ... 4 for sheet in sheetList: 5 ...
修改工作表
1 # 修改工作表使用的是xlutils, 其實也可以用xlwt, 2 # 我沒有用,原因:用資料上demo,demo使用的是這個,雖然demo沒有跑通 3 from xlutils.copy import copy 4 ... 5 wb = open_workbook(path + '/' + name) 6 ... 7 # 復制原文件,因為原文件只能讀取,不能寫入數據,所以要復制得到一個可以寫入數據的文件 8 newwb = copy(wb) 9 ... 10 for row in sheet.get_rows(): 11 # 遍歷每一行,當8列的值小於12時,就把該值改為0 12 if row[0].value < 12: 13 newsheet.write(index, 0, 0) 14 ...
保存
newwb.save('./data/' + name)
文件下的excel文件
獲取文件列表
1 import os 2 os.listdir(path)
功能如下:

全部代碼如下:
1 # -*- coding: utf-8 -*- 2 from xlrd import open_workbook 3 from xlutils.copy import copy 4 import os 5 6 7 def editExl(path, name): 8 if os.path.exists('/data'): 9 os.removedirs("/data") 10 # 括號里放入要讀取的文件的絕對路徑,相對路徑也可以 11 # os.getcwd() 返回當前.py文件所在的絕對路徑 12 # print(os.getcwd(), 'lujing') 13 wb = open_workbook(path + '/' + name) 14 # 獲取所讀取文件的第一張表單 15 # sheet = wb.sheet_by_index(0) 16 # 獲取該表單的行數 17 # s = sheet.nrows 18 19 20 # 獲取當前文件的工作表(sheet)list 21 sheetList = wb.sheets() 22 # print('sheetList', sheetList) 23 24 25 # 復制原文件,因為原文件只能讀取,不能寫入數據,所以要復制得到一個可以寫入數據的文件 26 newwb = copy(wb) 27 sheetIndex = 0 28 for sheet in sheetList: 29 30 31 # 獲取可寫文件的第一張表單 32 newsheet = newwb.get_sheet(sheetIndex) 33 # print(newsheet, newsheet.get_rows()) 34 index = 0 35 try: 36 for row in sheet.get_rows(): 37 # 遍歷每一行,當8列的值小於12時,就把該值改為0 38 # print(row) 39 # print(row[0].value, '000000000000000') 40 if row[0].value < 12: 41 # print('here', index) 42 newsheet.write(index, 0, 0) 43 # print('after here') 44 index = index + 1 45 except: 46 print("aaa") 47 sheetIndex = sheetIndex + 1 48 49 50 mkdir('./data') 51 newwb.save('./data/' + name) 52 53 54 def mkdir(path): 55 folder = os.path.exists(path) 56 if not folder: 57 os.makedirs(path) 58 print('--- folder mk ---') 59 else: 60 print('--- folder exists ---') 61 62 63 def getFileList(path): 64 return os.listdir(path) 65 66 67 def editAll(): 68 originPath = './origin' 69 fileList = getFileList(originPath) 70 # print(fileList) 71 for fileItem in fileList: 72 editExl(originPath, fileItem) 73 editAll()
