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

亡梦爱人 提交于 2019-12-01 11:55:20

问题


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 into another file.


回答1:


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')


来源:https://stackoverflow.com/questions/9125465/how-to-sort-xls-file-column-wise-and-write-it-to-another-file-with-entire-row-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!