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

发布于 2025-01-01 14:37:55 字数 79 浏览 4 评论 0原文

如何使用 python 按列对 xls 文件进行排序并将其写入另一个包含整行的文件? xls 文件必须按列排序。排序后必须将其写入另一个文件中。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不喜欢何必死缠烂打 2025-01-08 14:37:55

怎么样:

     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)

我的错,我猜你总是可以导出为 csv。如果您想坚持使用 xls,可以使用 xlrd 和 xlwt。我对此没有做过太多工作,但我确实有一个来自我不久前必须完成的任务的示例。就是这样(并不是 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')

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文