2012-12-12 32 views
2

腳本的目標是從每天從cron作業生成的excel文件中獲取數據&將該數據追加到「master」excel的底部文件。目標:讀取1 excel文件並將數據追加到第二個excel文件中

這裏就是我現在:

# Find the most recent excel file created by the cron job & open it. 

localtime = time.localtime(time.time()) 
yy = localtime.tm_year 
mm = localtime.tm_mon 
dd = localtime.tm_mday 

file_name = 'daily_' + str(yy) + '_' + str(mm) + '_' + str(dd-1) + '.xls' 
file_loc = '/Users/' + file_name 
new_sheet = open_workbook(file_loc, on_demand=True).sheet_by_index(0) 

# Grab all the data from the recent cron job file starting at row 2 to avoid 
# including headers. 

for row in range(1, new_sheet.nrows): 
    values = [] 
    for col in range(new_sheet.ncols): 
     values.append(new_sheet.cell(row,col).value) 
""" 
The above loop structures the list 'values[]' in a way that the print 
statement of value looks like the below output; which matches the formatting of 
master_file.xlsx: 

     2341511 Sports 12112 Dog 324.92 
     71611 Other 18192 Cat 128.17 
     ... 
""" 

# Find the excel master file & open it. 

sheet = open_workbook('master_file.xlsx').sheet_by_index(0) 

# Find the first row that is empty. 
new_row = sheet.nrows + 1 

# Append the values[] list to the master file starting at row(new_row) and save 
# the db file. 

for row_num, row in enumerate(values, new_row): 
    for col_num, col in enumerate(row): 
     sheet.row(row_num).write(col_num, col) 

sheet.save('master_file.xlsx') 

我的追蹤誤差爲:

File "daily.py", line 45, in <module> 
    sheet.row(row_num).write(col_num, col) 
    File "/Users/code/env/lib/python2.7/site-packages/xlrd/sheet.py", line 462, in row 
    for colx in xrange(len(self._cell_values[rowx])) 
IndexError: list index out of range 

任何幫助將不勝感激!

回答

1

從代碼中直觀地看出,在迭代之前,您並未實際向工作表添加行。

xlrd看起來並不像它實際上有修改現有工作表的方法。看看這個SO後這可能有助於...

How to add new column and row to .xls file using xlrd

+0

我假設我不必向工作表中添加一行,因爲所有的寫入操作都是使用xlwt&write函數處理的。也許我錯了xlrd和xlwt如何一起玩。 –

+0

感謝您的鏈接。我完全需要xlUtils。好極了! –

+0

祝你好運!如果這有幫助,可以隨時標記爲已回答和/或已滿足;) – jsh

0

您的意思是有col(new_row)而不是col,如:

for row_num, row in enumerate(values, col(new_row)): 
    for col_num, col(new_row) in enumerate(row): 
     sheet.row(row_num).write(col_num, col(new_row)) 

+0

對不起你我貼錯了for循環。編輯到正確的一個。然而,兩者都給了Indexerror。 –

+0

@DudeAbides那麼它可能是一個錯誤的1錯誤,你是否試圖抵消索引1? –

+0

我試圖在兩個方向上將new_row上的索引偏移1,但沒有運氣。我會繼續修補它,我想。 –