简体   繁体   English

使用Python从Excel排序列数据

[英]Sorting Column Data from Excel using Python

Is there a way to take the columns from an excel sheet, write the columns as lists, sort them, and then rewrite them to another excel sheet? 有没有办法从Excel工作表中提取列,将这些列写为列表,对其进行排序,然后将其重写为另一个Excel工作表? This is what I've tried so far, but it only writes the last column of data. 到目前为止,这是我尝试过的方法,但是它仅写入数据的最后一列。 I do not need the first 2 rows of data, as they are just headers. 我不需要前两行数据,因为它们只是标题。

import xlrd
import xlsxwriter

wb = xlrd.open_workbook('exceldata.xlsx')
ws = wb.sheet_by_index(0)

col=[]

for i in range(2,ws.ncols):
    col=ws.col_values(i)

    for x in range(2):
        col.pop(0)

    col.sort()

    workbook = xlsxwriter.Workbook('test_sorting.xlsx')
    worksheet = workbook.add_worksheet()
    worksheet.write_column('A1',col)
    workbook.close()

UPDATE: This is successful, but does anyone know how this can be simplified? 更新:这是成功的,但是有人知道如何简化吗?

import xlrd
import xlsxwriter

wb = xlrd.open_workbook('exceldata.xlsx')
ws = wb.sheet_by_index(0)


col1=ws.col_values(2)
for x in range(2):
    col1.pop(0)
col1.sort()

col2=ws.col_values(3)
for x in range(2):
     col2.pop(0)
col2.sort()

col3=ws.col_values(4)
for x in range(2):
     col3.pop(0)
col3.sort()

col4=ws.col_values(5)
for x in range(2):
    col4.pop(0)
col4.sort()

col5=ws.col_values(6)
for x in range(2):
     col5.pop(0)
col5.sort()

columns=[]
for i in range(2,7):
    col=ws.col_values(i)
    columns.append(col)

print(columns)

workbook = xlsxwriter.Workbook('test_sorting.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write_column('A2',col1)
worksheet.write_column('B2',col2)
worksheet.write_column('C2',col3)
worksheet.write_column('D2',col4)
worksheet.write_column('E2',col5)

workbook.close() workbook.close()

I think you need to append() or extend() column names from your excel to the list 'col'. 我认为您需要将Excel中的column()或extend()列名称添加到列表“ col”。 currently it is replacing the value of 'i' every time the FOR loop iterates. 当前,每次FOR循环迭代时,它都将替换“ i”的值。

maybe something like this: col.append(ws.col_values(i)) 也许是这样的:col.append(ws.col_values(i))

PS This is my first answer on stack-overflow. PS:这是我对堆栈溢出的第一个答案。 hope it helps. 希望能帮助到你。 I have not tested it (I will test it and update the answer if required). 我尚未测试(如果需要,我将对其进行测试并更新答案)。

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

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