Python – 使用csv和xlrd模块将多行excel文件写入一行csv文件

我有一个基本的脚本,将采取源Excel(.xlsx)文件,并将数据写入python中匹配的CSV文件。 我的最终目标是把所有的数据放在一张表中,并把它写成一个长逗号分隔的行,我不知道如何完成这个到目前为止的基础。

def csv_from_excel(): import csv import xlrd wb1 = raw_input('What is the path and file name of your Workbook? ') sh = raw_input('What is the name of the sheet being transformed? ') csv_file1 = raw_input('What is the file path and name of the output? ') print wb1 print sh print csv_file1 wb = xlrd.open_workbook(wb1) sh1 = wb.sheet_by_name(sh) csv_file = open(csv_file1, 'wb') wr = csv.writer(csv_file, quoting=csv.QUOTE_MINIMAL) for rownum in xrange(sh1.nrows): wr.writerow(sh1.row_values(rownum)) csv_file.close() print "Completed converting %s and %s to csv" % (wb1, sh) csv_from_excel() 

如果我理解正确,您想要采取多行XLS并输出为单行CSV。 如果是这样,这会导致您输出多个CSV行:

 for rownum in xrange(sh1.nrows): wr.writerow(sh1.row_values(rownum)) 

该代码遍历XLS中的每一行,并在CSV中创build相应的行。 由于您只需要一个CSV行,因此您应该先将XLS行累积到一个集合中,然后再将其全部写入一步:

 output = list() for rownum in xrange(sh1.nrows): output.extend(sh1.row_values(rownum)) wr.writerow(output)