简体   繁体   English

如何对xls文件按列进行排序,并使用python将其写入整个行的另一个文件中?

[英]how to sort xls file column wise and write it to another file with entire row using python?

how to sort xls file column wise and write it to another file with entire row using python ? 如何对XLS文件按列进行排序,然后使用python将其写入整个行的另一个文件中? the xls file has to be sorted column wise. xls文件必须按列进行排序。 And after sorting it has to be writen into another file. 排序后,必须将其写入另一个文件。

How about: 怎么样:

     column = 0 #The column you want to sort by
     reader = list(csv.reader(open('input.xsl')))
     reader.sort(key=lambda x: x[column])
     writer = csv.writer(open('output.xsl', 'w'))
     writer.writerows(reader)

My bad, well you can always export as csv i guess. 我的坏,好吧,我总是可以导出为csv。 If you want to stick to xls you can use xlrd and xlwt. 如果要坚持使用xls,则可以使用xlrd和xlwt。 I haven't worked much with this but I do have a sample from a task I had to do a while back. 我并没有为此做很多工作,但是我确实有一段时间不得不做的任务的样本。 Here it is(not that is not 100% good because the cell titles for each columns will be stored as the first row on data on the output file): 在这里是(不是那不是100%好的,因为每列的单元格标题将作为第一行存储在输出文件上的数据中):

    import xlwt
    from xlrd import open_workbook

    target_column = 0

    book = open_workbook('input.xls', formatting_info=True)
    sheet = book.sheets()[0]
    data = [sheet.row_values(i) for i in xrange(sheet.nrows)]
    labels = data[0]
    data = data[1:]
    data.sort(key=lambda x: x[target_column])

    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet(sheet.name)

    for idx, label in enumerate(labels):
         sheet.write(0, idx, label)

    for idx_r, row in enumerate(data):
        for idx_c, value in enumerate(row):
            sheet.write(idx_r+1, idx_c, value)

    wbk.save('result.xls')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM