Step 1:
Install openpyxl if you haven't already. You can install it using pip:
Step 2:
pip install openpyxl
import openpyxl
# Open the Excel file
input_file_path = 'input.xlsx' # Replace with the path to your input Excel file
output_file_path = 'output.xlsx' # Replace with the path to the output Excel file
workbook = openpyxl.load_workbook(input_file_path)
# Select a specific worksheet
worksheet = workbook.active # You can also use workbook['SheetName'] to select by name
# Iterate through rows and columns to read and trim data
for row in worksheet.iter_rows(values_only=True):
for cell in row:
if cell is not None and isinstance(cell, str):
cell.value = cell.value.strip() # Remove trailing spaces from string cells
# Create a new Excel file with the trimmed data
workbook.save(output_file_path)
# Close the Excel files
workbook.close()
print("Excel file processing completed.")