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

Python - Using csv and xlrd module to write multi-row excel file to one row csv file

我有一个基本脚本,它将获取源 excel (.xlsx) 文件并将数据写入 python 中匹配的 csv 文件。我的最终目标是获取 sheet 中的所有数据并将其写成一个用逗号分隔的长行,但我不确定如何根据我目前所掌握的内容来完成此操作。

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 中创建相应的行。由于您只需要一个 CSV 行,因此您应该先将 XLS 行累积到一个集合中,然后再一步将其全部写出:

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