2015-02-23 50 views
1

我是新來的編程和Python(使用python27),我試圖編寫代碼來打開多個Excel文件從一個特定的文件夾,抓取特定的單元格值,然後輸出到單個excel文件,每行代表打開每個文件的記錄。打開多個XL文件,抓取數據,然後寫入熊貓/輸出到單個Excel文件

這裏是我的代碼,我被困在接下來的過程中應該是什麼:

import os 
import glob 
import xlrd 
import datetime 


yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1) 

for root,dirs,files in os.walk(src): 
    files = [ _ for _ in files if _.endswith('.xlsx') ] 

for xlsfile in files: 
    wb = xlrd.open_workbook(os.path.join(root,xlsfile)) 
    sht = wb.sheet_by_name('Sheet1') 
    name = xlsfile 
    rev = sht.cell_value(0,1) 
    gp = sht.cell_value(1,1) 
    sls = sht.cell_value(2,1) 
    sp = sht.cell_value(3,1) 
    cps = sht.cell_value(4,1) 
    print yesterday, name, rev, gp, sls, sp, cps 

回答

0

這裏的變化,以輸出到xls文件::

import os 
import glob 
import pyexcel as pe 
import pyexcel.ext.xls 
import xlrd 
import datetime 


yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1) 

for root,dirs,files in os.walk(src): 
    files = [ _ for _ in files if _.endswith('.xlsx') ] 

array = [] 

for xlsfile in files: 
    wb = xlrd.open_workbook(os.path.join(root,xlsfile)) 
    sht = wb.sheet_by_name('Sheet1') 
    name = xlsfile 
    rev = sht.cell_value(0,1) 
    gp = sht.cell_value(1,1) 
    sls = sht.cell_value(2,1) 
    sp = sht.cell_value(3,1) 
    cps = sht.cell_value(4,1) 
    array.append([yesterday, name, rev, gp, sls, sp, cps]) 
    print yesterday, name, rev, gp, sls, sp, cps 

pe.save_as(array=array, "myfile.xls") 

更多的文檔可發現here

+0

謝謝,這工作!我實際上調整它輸出到一個熊貓數據框架,然後出到一個csv。再次感謝你! – gall3on 2015-02-23 17:31:59

+0

要保存爲csv,您可能需要:pe.save_as(array = array,「myfile.csv」)。但我很高興下一步幫助你繼續。 – chfw 2015-02-23 20:23:44

相關問題