Excel is a powerful tool that can be used for a variety of purposes. However, sometimes we need to perform certain operations on Excel files using programming languages like Python.
In this tutorial, we will go through the steps necessary to append a row in Excel using Python.
Step 1: Import Necessary Libraries
To manipulate Excel files using Python, we need to import two libraries: pandas
and openpyxl
. Pandas is a library for data manipulation and analysis while openpyxl is a library for working with Excel files.
1 |
# Import libraries<br>import pandas as pd<br>from openpyxl import load_workbook |
Step 2: Load Excel File
To append a row to an existing Excel file, we must first load the file using the load_workbook
function from the openpyxl
library. This function takes the path to the Excel file as an argument and returns a workbook
object.
1 |
# Load workbook<br>workbook = load_workbook(filename='example.xlsx') |
Step 3: Select Worksheet
Once we have loaded the Excel file, we need to select the worksheet to which we want to append the row. This can be done using the active
attribute of the workbook
object, which returns the currently active worksheet.
1 |
# Select worksheet<br>worksheet = workbook.active |
Step 4: Define Row
Before we can append a row to the worksheet, we need to define the data for the row. We can do this by creating a list containing the values for each cell in the row.
1 |
# Define row<br>new_row = ['John', 'Doe', '25', 'Male'] |
Step 5: Append Row
Finally, we can append the row to the worksheet using the append
method of the worksheet
object. This method takes the row data as an argument and adds it as a new row at the end of the worksheet.
1 |
# Append row<br>worksheet.append(new_row) |
Step 6: Save Excel File
Once we have appended the row to the worksheet, we need to save the changes to the Excel file using the save
method of the workbook
object.
1 |
# Save workbook<br>workbook.save(filename='example.xlsx') |
And that’s it! We have successfully appended a row to an existing Excel file using Python.
Here’s the complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Import libraries import pandas as pd from openpyxl import load_workbook # Load workbook workbook = load_workbook(filename='example.xlsx') # Select worksheet worksheet = workbook.active # Define row new_row = ['John', 'Doe', '25', 'Male'] # Append row worksheet.append(new_row) # Save workbook workbook.save(filename='example.xlsx') |
If you want to learn more about working with Excel files using Python, check out the openpyxl
documentation: https://openpyxl.readthedocs.io/en/stable/.