简体   繁体   中英

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? 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()

I think you need to append() or extend() column names from your excel to the list 'col'. currently it is replacing the value of 'i' every time the FOR loop iterates.

maybe something like this: col.append(ws.col_values(i))

PS This is my first answer on stack-overflow. hope it helps. I have not tested it (I will test it and update the answer if required).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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