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

后端 未结 1 598
梦毁少年i
梦毁少年i 2021-01-16 09:40

how to sort xls file column wise and write it to another file with entire row using python ? the xls file has to be sorted column wise. And after sorting it has to be writen

相关标签:
1条回答
  • 2021-01-16 09:50

    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. If you want to stick to xls you can use xlrd and 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):

        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')
    
    0 讨论(0)
提交回复
热议问题