example using openpyxl to add a new entry in a table in python

In order to add a new entry in a table using openpyxl and Python, you can use the following steps:

  1. Load the workbook using load_workbook() method of openpyxl module.
  2. Get the sheet that contains the table using worksheet = workbook['Sheet1'].
  3. Find the table in the sheet using table = worksheet.tables['Table1'].
  4. Create a new row using new_row = ['value1', 'value2', 'value3'] where value1, value2, and value3 are the values that you want to add in the table.
  5. Add the new row in the table using table.add_row(new_row) method.
  6. Save the changes using workbook.save('example.xlsx') method.

Here's the code snippet that demonstrates these steps:

main.py
from openpyxl import load_workbook

# Step 1 - Load the workbook
workbook = load_workbook('example.xlsx')

# Step 2 - Get the sheet
worksheet = workbook['Sheet1']

# Step 3 - Find the table
table = worksheet.tables['Table1']

# Step 4 - Create a new row
new_row = ['value1', 'value2', 'value3']

# Step 5 - Add the new row in the table
table.add_row(new_row)

# Step 6 - Save the changes
workbook.save('example.xlsx')
418 chars
20 lines

Make sure to replace the 'example.xlsx' with the name of your workbook file and 'Sheet1' and 'Table1' with the name of your sheet and table, respectively.

related categories

gistlibby LogSnag