【问题标题】:OPENPYXL sorted data in EXCEL columnOPENPYXL 在 EXCEL 列中排序的数据
【发布时间】:2023-01-20 13:36:16
【问题描述】:

我想在我的 Excel 文件中按 C 列保存从 A 到 Z 的排序数据。

我的代码:

### EXCEL
# Set column names
A = 'SURNAME'
B = 'NAME'
C = 'sAMAccountName'

# Set worksheet
wb = Workbook() # create excel worksheet
ws_01 = wb.active # Grab the active worksheet
ws_01.title = "all inf" # Set the title of the worksheet
# Set first row
title_row = 1
ws_01.cell(title_row, 1, A) # cell(row, col, value)
ws_01.cell(title_row, 2, B)
ws_01.cell(title_row, 3, C)

data_row = 2
for user in retrieved_users:
    attributes = user['attributes']
    sAMAccountName = attributes['sAMAccountName']
    if(user_validation(sAMAccountName) == True):
        A = attributes['sn']
        B = attributes['givenName']
        C = sAMAccountName
        ws_01.cell(data_row, 1, str(A))
        ws_01.cell(data_row, 2, str(B))
        ws_01.cell(data_row, 3, str(C))
        data_row = data_row + 1
    
# Save it in an Excel file
decoded_users_all_inf = root_path + reports_dir + users_all_inf_excel_file
wb.save(decoded_users_all_inf)

我在哪里以及我的代码中添加了什么?

【问题讨论】:

  • 最好的办法是在写入 Excel 之前对数据进行排序。您可以向工作表添加过滤器,以便用户可以对 Excel 中的列进行排序,但排序必须手动执行。

标签: python python-3.x openpyxl


【解决方案1】:

如果你想对retrieved_users进行排序,那么你可以使用内置的list.sortkey来访问sAMAccountName

retrieved_users = [
    {"attributes": {"sn": "a", "givenName": "Alice", "sAMAccountName": "z"}},
    {"attributes": {"sn": "b", "givenName": "Bob", "sAMAccountName": "x"}},
    {"attributes": {"sn": "c", "givenName": "Charlie", "sAMAccountName": "y"}},
    ]

retrieved_users.sort(key=lambda d: d["attributes"]["sAMAccountName"])

retrieved_users包含

[{'attributes': {'sn': 'b', 'givenName': 'Bob', 'sAMAccountName': 'x'}},
 {'attributes': {'sn': 'c', 'givenName': 'Charlie', 'sAMAccountName': 'y'}},
 {'attributes': {'sn': 'a', 'givenName': 'Alice', 'sAMAccountName': 'z'}}]

另一方面,您可以执行 ws.append(row) 一次附加整行,而不是执行 ws.cell(row, col, value) 三次:

wb = Workbook()
ws = wb.active

ws.append(('SURNAME', 'NAME', 'sAMAccountName'))

相当于

wb = Workbook()
ws = wb.active

ws.cell(1, 1, 'SURNAME')
ws.cell(1, 2, 'NAME')
ws.cell(1, 3, 'sAMAccountName')

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 2021-10-05
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多