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

本文介绍了如何使用Python的xlrd库读取xls文件,根据指定列进行排序,然后利用xlwt将排序后的数据写入新的xls文件。提供了完整的代码示例,包括读取、排序和写入过程。适用于需要对xls文件进行数据处理的场景。
摘要由CSDN通过智能技术生成

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.

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值