2013-07-01 28 views
0

我想從多個文件中提取標題行(第一行),每個文件都有多個工作表。每張紙的輸出應保存並放入一個新的主文件中,該文件包含每張紙和每個文件的所有標題。在工作簿中保存row_slice信息xlrd python

我發現的最簡單的方法是使用命令row_slice。但是,文件的輸出是一個Cell對象列表,我似乎無法訪問它們的索引。

我正在尋找一種方法將提取的數據保存到新的工作簿中。

這裏是我到目前爲止的代碼:

from xlrd import open_workbook,cellname 
book = open_workbook('E:\Files_combine\MOU worksheets 2012\Walmart-GE_MOU 2012-209_worksheet_v03.xls') 
last_index = len(book.sheet_names()) 
for sheet_index in range(last_index): 
sheet = book.sheet_by_index(sheet_index) 
print sheet.name 
print sheet.row_slice(0,1) 

我不能得到的輸出,並將其存儲作爲輸入到一個新的文件。此外,任何想法如何自動化這個過程100 +文件將不勝感激。

回答

1

可以輸出存儲在一個CSV文件,你可以在所有的文件名使用os.listdir和for循環迴路

import csv 
import os 

from xlrd import open_workbook, cellname 

EXCEL_DIR = 'E:\Files_combine\MOU worksheets 2012' 
with open("headers.csv", 'w') as csv_file: 
    writer = csv.writer(csv_file) 
    for file_name in os.listdir(EXCEL_DIR): 
     if file_name.endswith("xls"): 
      book = open_workbook(os.path.join(EXCEL_DIR, file_name)) 
      for index, name in enumerate(book.sheet_names()): 
       sheet = book.sheet_by_index(index) 
       #the write row method takes a sequence 
       #I assume that row_slice returns a list or a tuple 
       writer.writerow(sheet.row_slice(0,1))