在工作簿xlrd python中保存row_slice信息

时间:2013-07-01 18:34:19

标签: python excel pydev xlrd xlwt

我正在尝试从多个文件中提取标题行(第一行),每个文件都有多个工作表。应保存每张工作表的输出并将其添加到新的主文件中,该文件包含每个工作表和每个文件的所有标题。

我找到的最简单的方法是使用命令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 个答案:

答案 0 :(得分: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))