【问题标题】:Python openpyxl insert new row in tablePython openpyxl在表中插入新行
【发布时间】:2021-11-27 00:50:42
【问题描述】:

我目前正在尝试在我的 Excel 文件中的表格中插入一个新行。 在互联网上我发现了这个:

    import openpyxl
    wb = openpyxl.load_workbook(excel_file_name)
    sheet = wb['Sheet1']
   
    sheet.insert_rows(1, amount=10)

    wb.save(excel_file_name)
    wb.close()

如果没有我的 excel 文件中的表格内容,它可以正常工作。将它与我的 excel 文件中的表一起使用它总是想恢复文件,因为它无法读取某些内容。

我的excel文件内容:

【问题讨论】:

  • 你的表格内容是什么?可能与这个问题中的问题有关Openpyxl created excel file with table causes file that requires recovery error
  • @chickitychinachinesechicken 姓氏、姓氏和地址...这个问题对我没有帮助,因为我想在现有表中插入一行。 ^^'
  • 您要插入一个新行还是 10 个新行? sheet.insert_rows(1, amount=10) 中的 amount=10 参数将在从索引 1 开始的第一行之前插入 10 行。
  • 您的代码建议您只想在索引 1 处为 Nr. 插入一行 value=10,您尝试过 sheet.insert_rows(idx=2, amount=1); sheet['B2']=10 吗?
  • 谢谢@chickitychinachinesechicken。这解决了我的问题。我将发布正确的代码作为答案!

标签: python openpyxl


【解决方案1】:

解决方法是在函数insert_rows(idx=row, amount=amount中使用,在表格中插入新行。

这是工作代码:

    import openpyxl
    wb = openpyxl.load_workbook(EXCEL_FILE_NAME)
    sheet = wb['Sheet1']

    sheet.insert_rows(idx=2, amount=1)
    cell_object = sheet.cell(
        row=2, column=1)
    cell_object.value = 11

    wb.save(EXCEL_FILE_NAME)
    wb.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2017-12-11
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    相关资源
    最近更新 更多