我有一个基本脚本,它将获取源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()
答案 0 :(得分:1)
如果我理解正确,您希望采用多行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)