To update data in an Excel file using Python, you can use the pandas
library. Here’s a sample code to update data in an Excel file
import pandas as pd # Read the Excel file excel_file = 'path/to/your/excel/file.xlsx' df = pd.read_excel(excel_file) # Update the data # Replace 'column_name' with the actual column name and 'condition_value' with the desired condition df.loc[df['column_name'] == 'condition_value', 'column_name'] = 'new_value' # Save the updated data to a new Excel file output_file = 'path/to/your/output/file.xlsx' df.to_excel(output_file, index=False) print("Data updated successfully!")
In the code above, replace 'path/to/your/excel/file.xlsx'
with the actual path to your Excel file. You also need to replace 'column_name'
with the actual column name you want to update and 'condition_value'
with the desired condition to identify the rows to be updated. Finally, replace 'path/to/your/output/file.xlsx'
with the desired path to the output file.
The code uses the pandas
library to read the Excel file into a DataFrame using the pd.read_excel()
function.
It then updates the data in the DataFrame using the loc
function, which allows you to select rows based on a condition and update specific columns.
Finally, the updated DataFrame is saved to a new Excel file using the to_excel()
function.
Make sure to have the pandas
library installed. You can install it using pip:
pip install pandas
Remember to handle any exceptions that may occur during file reading, updating, or writing for proper error handling.