将数据导出到空单元格行Openpyxl

时间:2019-11-04 15:46:19

标签: python-3.x openpyxl

我正在尝试通过使用openpyxl将数据导出到ms excel来自动化几个列表的数字分组。输出是一个列表列表,每个元素具有两组数字,第一组是匹配的数字(0到99),第二组是它们匹配的索引号。

def variable_str_to_list_pairs_overlapping (str):
    return [''.join(pair) for pair in zip(str[:-1], str[1:])]

list1 = variable_str_to_list_pairs_overlapping (list1)
list2 = variable_str_to_list_pairs_overlapping (list2)

lst_result = []
for i in range(len(list2)):
     if list1[i] == list2[i]:
     data = [list1[i], i]
     data[0] = int(list1[i])
     lst_result.append(data)
print(lst_result)

输出:

    [[7, 265], [8, 281], [2, 303], [8, 332], [7, 450], [1, 544], [0, 
    737], [9, 805], [2, 970], [4, 1103], [4, 1145], [8, 1303], [1, 
    1575], [4, 1592], [2, 1593], [3, 1948], [4, 2200], [5, 2419], [3, 
    2464], [9, 2477], [1, 2529], [6, 2785], [2, 2842], [8, 2843], [7, 
    2930], [3, 2991], [8, 3096], [3, 3248], [2, 3437], [7, 3438], [8, 
    3511], [0, 3522], [0, 3523], [5, 3590], [6, 3621], [1, 3622], [2, 
    3671], [6, 3835], [7, 3876]]

我希望将数据导出到excel,以便将第一个元素分配为行索引,将第二个元素分配为单元格内部的值

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
dest_filename = 'openpyxltest.xlsx'
for x in lst_result:
    ws.cell(row = x[0] + 1, column = +2).value = x[1]
wb.save(filename = dest_filename)

实际输出: Actual Output

所需的输出: Desired Output

我需要在代码中进行哪些更改?预先感谢您的帮助。你们真棒! :)

1 个答案:

答案 0 :(得分:0)

您正在覆盖单元格-您从不调整要写入的-因此以后的写操作会覆盖它...

您可以通过使用defaultdict(list)将一个键的所有值收集到列表中,对其进行排序,然后像下面这样从字典中创建xlsx来解决此问题:

lst_result = [[7, 265], [8, 281], [2, 303], [8, 332], [7, 450], [1, 544], [0, 
    737], [9, 805], [2, 970], [4, 1103], [4, 1145], [8, 1303], [1, 
    1575], [4, 1592], [2, 1593], [3, 1948], [4, 2200], [5, 2419], [3, 
    2464], [9, 2477], [1, 2529], [6, 2785], [2, 2842], [8, 2843], [7, 
    2930], [3, 2991], [8, 3096], [3, 3248], [2, 3437], [7, 3438], [8, 
    3511], [0, 3522], [0, 3523], [5, 3590], [6, 3621], [1, 3622], [2, 
    3671], [6, 3835], [7, 3876]]

from collections import defaultdict

# group all datapoints by 1st value
grpd_data = defaultdict(list)
for k,v in lst_result:
    grpd_data[k].append(v)

# sort all grouped values (not needed here, as inputs are sorted)
# for l in grpd_data:
#    grpd_data[l].sort()

grpd_data如下:

# defaultdict(<type 'list'>, {0: [737, 3522, 3523], 1: [544, 1575, 2529, 3622], 
#     2: [303, 970, 1593, 2842, 3437, 3671], 3: [1948, 2464, 2991, 3248], 
#     4: [1103, 1145, 1592, 2200], 5: [2419, 3590], 6: [2785, 3621, 3835], 
#     7: [265, 450, 2930, 3438, 3876], 8: [281, 332, 1303, 2843, 3096, 3511], 
#     9: [805, 2477]})

然后创建工作簿:

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
dest_filename = 'openpyxltest.xlsx'

for x,data in grpd_data.items():
    ws.cell(row = x + 1, column = 1).value = x
    for col,d in enumerate(data,2): 
        ws.cell(row = x + 1, column = col).value = d

wb.save(filename = dest_filename)

输出:

resulting xlsx


请参阅: