Created
July 20, 2023 22:19
-
-
Save Sven-Bo/bfadc04ff474b9b8976583f18324460b to your computer and use it in GitHub Desktop.
Python script to append DataFrame data to an Excel table using xlwings
This file contains hidden or 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
# This code was provided by Sven Bosau | |
# Website: https://pythonandvba.com | |
# YouTube: https://youtube.com/@codingisfun | |
import xlwings as xw | |
import pandas as pd | |
# Constants | |
WORKBOOK_PATH = 'workbook.xlsx' | |
SHEET_NAME = 'Sheet1' | |
TABLE_NAME = 'Table1' | |
# Assuming this is your DataFrame | |
df = pd.DataFrame({ | |
'Column1': ['New data 1', 'New data 2'], | |
'Column2': ['More new data 1', 'More new data 2'] | |
}) | |
# Convert your DataFrame to a list of lists | |
new_data = df.values.tolist() | |
# Use context manager to handle the workbook | |
with xw.Book(WORKBOOK_PATH) as wb: | |
# Select your table | |
sht = wb.sheets[SHEET_NAME] | |
table = sht.range(TABLE_NAME) | |
# Append your data | |
table.value = table.value + new_data | |
# Save your workbook | |
wb.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment