write table in excel file using openpyxl in python

Here's an example of how to write a table in an existing Excel file using openpyxl library in Python:

main.py
import openpyxl

# Load the workbook
workbook = openpyxl.load_workbook('example.xlsx')

# Select the worksheet
worksheet = workbook.active

# Create table headers
table_headers = ['Name', 'Age', 'Salary']

# Append headers to the first row
worksheet.append(table_headers)

# Add some data
data_rows = [
    ('John', 30, 50000),
    ('Sara', 25, 35000),
    ('Bob', 35, 70000)
]

# Append rows to the worksheet
for row in data_rows:
    worksheet.append(row)

# Save the changes to the workbook
workbook.save('example.xlsx')
524 chars
28 lines

The code above uses openpyxl to load an existing Excel file and select a worksheet. It then creates a table header row and appends it to the worksheet.

Next, some example data is defined and the rows are also appended to the worksheet. Finally, the changes are saved to the workbook using workbook.save().

related categories

gistlibby LogSnag