使用 for 循环写入 Excel 文件

writing Excel file while using for loop

我试图在 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)

我没有 xlsxwriter,所以无法测试。文档说它不能修改现有文件所以我怀疑 for x in List: 的每次迭代都是 over-writing 你的文件 (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)

更改函数以迭代这些命令;为每个

制作一个新的sheet
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()