0

for我正在尝试在循环期间将数据写入 Excel 文件。但我得到的是包含循环接收到的最后一个数据的单行。

我尝试了几种不同的方法,但都失败了。下面列出了 2 次尝试

有任何想法吗 ?

def write_excel(x):
    workbook = xlsxwriter.Workbook('ID_Num.xlsx')
    worksheet = workbook.add_worksheet()

    df = pd.DataFrame(
        {'ID':[x],
         'mail_one':[Email],
         'second_mail':[second_mail],
         'Num':[Num],
         'date':[Date]})

    row_num = 0
    for key, value in df.items():
        worksheet.write(0, row_num, key)
        worksheet.write_row(1, row_num, value)
        row_num += 1

    workbook.close()

    #df = pd.DataFrame(
    #    {'ID':[x],
    #     'mail_one':[Email],
    #     'second_mail':[second_mail],
    #     'Num':[Num],
    #     'date':[Date]})

    # writer = ExcelWriter('ID_Num.xlsx')
    # df.to_excel(writer,'ID_Num',index=False)

    # writer.save()


if __name__ == "__main__":
    for x in List:
        my_dic = {}
        my_dict["ID"] = x
        my_dict["mail_one"] = Email
        my_dict["second_mail"] = second_mail
        my_dict["Num"] = str(Num)
        my_dict["date"] = Date
        print(my_dict)
        write_excel(x)

4

1 回答 1

1

我没有 xlsxwriter,所以我无法测试。该文档说它无法修改现有文件,因此我怀疑您的每次迭代for x in List:都在覆盖您的文件(workbook = xlsxwriter.Workbook('ID_Num.xlsx'))。

您可以使用以下更改创建多个文件:

def write_excel(x,i):
    workbook = xlsxwriter.Workbook(f'ID_Num{i}.xlsx')
    ...
# and
for i,x in enumerate(List):
    ...
    write_excel(x,i)

或者您可以累积多个字典并将它们全部传递给您的函数

data = []
for x in List:
    my_dic = {}
    ...
    data.append(my_dic)
write_excel(data)

更改函数以迭代这些字典;为每个人制作一张新工作表

def write_excel(data):
    workbook = xlsxwriter.Workbook('ID_Num.xlsx')
    for sht in data:
        worksheet = workbook.add_worksheet()
        df = pd.DataFrame(...

        row_num = 0
        for key, value in df.items():
            worksheet.write(...
            worksheet.write_row(...
            row_num += 1

    workbook.close()
于 2020-10-20T16:37:49.587 回答