You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用openpyxl的sheet.insert_rows()批量插入行后Excel文件损坏的问题求助

使用openpyxl的sheet.insert_rows()批量插入行后Excel文件损坏的问题求助

嘿各位,我最近在写Python脚本,想用openpyxl把字典列表的数据填充到Excel工作表中间的一个表格里(这个表格不是从A1开始的),结果遇到了一个棘手的问题——批量插入行之后Excel文件直接损坏了,想请大家帮忙看看哪里出问题了!

问题场景

我先写了一段定位表格起始位置的逻辑:遍历工作表找到包含“Project”的行作为表头,然后确定表头所在的列和要开始插入数据的行(表头行的下两行)。我的想法是每插入一条数据就先在目标位置插入一行,再把数据填进去,这样不会覆盖表格下方用于计算的单元格。

单条数据插入的时候完全没问题,Excel能正常打开;但一用循环批量插入多条数据,保存后的文件就损坏了——打开时会弹出:

we found a problem with some content in 'finaltemplaterrrrr.xlsx' , do you want us to try to recover as much as we can ? if you trust the source of this workbook, click yes.

点“是”之后文件还直接关闭了,根本看不到修复后的内容。

我的代码

这是我写的方法:

def generateExcel(data_list):
    file_path = 'Finaltemplatetesting.xlsx'
    sheet_name = 'Main'

    workbook = openpyxl.load_workbook(file_path)
    # Select the sheet
    sheet = workbook[sheet_name]

    # Find the starting cell (top-left cell) of the table
    i=0
    for row in sheet.iter_rows(values_only=True):
        i=i+1
        if 'Project' in row:
            header_row = row
            break

    header_col = header_row.index('Project')
    # initializing the starting row
    start_row=i+2

    # Fill the table with the new data
    for data in data_list:
        sheet.insert_rows(start_row)
        for row_data in data:
            for col_idx, col_name in enumerate(header_row):
                cell = sheet.cell(row=start_row, column=header_col + col_idx, value=row_data.get(col_name))
        start_row += 1

    workbook.save("Finaltempalterrrrrr.xlsx")

测试用的dummy数据:

[
    [{'Value1': '15', 'Project': 'AVTR', 'Score': 'Normal', 'Name': 'Raul', 'Date': '2023-03-16T14:58:33+01:00'}],
    [{'Value1': '10', 'Project': 'TRG', 'Score': 'High', 'Name': 'Bob', 'Date': 'N/A'}],
    [{'Value1': '12', 'Project': 'AVTR', 'Score': 'High', 'Name': 'Alice', 'Date': 'N/A'}]
]

我试过的操作

  • 只插入单条数据时,代码能正常运行,Excel文件也没问题,插入的位置和数据都正确;
  • 但只要一用循环批量插入,就会出现文件损坏的情况。

有没有大佬能帮我看看是哪里的逻辑出问题了?感激不尽!

备注:内容来源于stack exchange,提问作者Louay GOURRIDA

火山引擎 最新活动