Created
November 20, 2023 09:28
-
-
Save sreejithpro/b94b155501d95669525dea4b6b976016 to your computer and use it in GitHub Desktop.
Open excel sheets, insert formulas into the worksheets, save and close.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import xlwings as xw | |
# Define the path to the folder containing the Excel files | |
folder_path = r"source folder" # <-- MODIFY THIS PATH | |
# Define the formulas to be inserted | |
formula1 = "=C14" # <-- Your Formula1 | |
# formula2 = "=MAX(G16,H16)" # <-- Your Formula2 | |
# formula3 = '=IF(I4="Your Criteria",J13,J14)' # <-- Your Formula3 | |
# Initialize Excel application with xlwings | |
app = xw.App(visible=False) | |
# Loop through each file in the specified folder | |
for file_name in os.listdir(folder_path): | |
file_path = os.path.join(folder_path, file_name) | |
if file_path.endswith(('.xlsm', '.xls', 'xlsx')): | |
# Open the workbook | |
workbook = app.books.open(file_path) | |
# Insert the formula into the specified sheet and cell | |
if 'Sheet1' in [sheet.name for sheet in workbook.sheets]: | |
sheet = workbook.sheets['Sheet1'] | |
sheet.range('C15').formula = formula1 | |
# sheet.range('I14').formula = formula2 | |
# if 'Sheet2' in [sheet.name for sheet in workbook.sheets]: | |
# sheet = workbook.sheets['Sheet2'] | |
# sheet.range('C17').formula = formula3 | |
# Save and close the workbook | |
workbook.save() | |
workbook.close() | |
# Quit the Excel application | |
app.quit() | |
# No need to explicitly clean up the COM objects as xlwings handles it internally. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment