Skip to content

Instantly share code, notes, and snippets.

@MagnetonBora
Created October 25, 2023 13:53
Show Gist options
  • Save MagnetonBora/e609f058e9fed9dc1d2541f08561bdf0 to your computer and use it in GitHub Desktop.
Save MagnetonBora/e609f058e9fed9dc1d2541f08561bdf0 to your computer and use it in GitHub Desktop.
This is an example of how to append some records to a given Excel spreadsheet without altering the rest of the spreadsheet, using pandas and openpyxl.
import openpyxl # for working with Excel files
import pandas as pd # for working with DataFrames
from openpyxl.utils.dataframe import dataframe_to_rows # for converting DataFrames to rows in Excel
# openpyxl and pandas need to be installed with pip
# Function to generate sample data as a DataFrame
def generate_sample_data():
return pd.DataFrame({
'Name': [
'Alice', 'Bob', 'Charlie', 'David', 'Eve',
'Frank', 'Grace', 'Helen', 'Ivy', 'Jack'
],
'Age': [25, 30, 35, 40, 45, 28, 32, 37, 42, 27],
'City': [
'New York', 'Los Angeles', 'Chicago', 'Houston',
'Miami', 'San Francisco', 'Boston', 'Dallas',
'Seattle', 'Atlanta'
],
'Salary': [
60000, 70000, 80000, 90000, 100000,
65000, 75000, 85000, 95000, 105000
],
'Department': [
'HR', 'IT', 'Sales', 'Finance', 'Marketing',
'IT', 'HR', 'Sales', 'Finance', 'Marketing'
]
})
# Function to write a DataFrame to an Excel file
def write_to_excel(df: pd.DataFrame, path: str, sheet_name: str = "Sheet1") -> None:
df.to_excel(path, sheet_name=sheet_name, index=False)
# Function to append a DataFrame to an existing Excel file or sheet
def append_to_excel(df: pd.DataFrame, path: str, sheet_name: str = "Sheet1") -> None:
# Load the existing Excel file
book = openpyxl.load_workbook(path)
target_sheet = None
# Check if the target sheet exists in the workbook
for sheet in book.worksheets:
if sheet.title == sheet_name:
target_sheet = sheet
break
if target_sheet is None:
# If the target sheet doesn't exist, create it
target_sheet = book.create_sheet(sheet_name)
# Append the rows from the DataFrame to the target sheet
for row in dataframe_to_rows(df, index=False, header=False):
target_sheet.append(row)
# Save the changes to the Excel file
book.save(path)
# Main function that generates sample data, writes it to an Excel file,
# appends the same data to the Excel file, and prints the DataFrame
def main():
df = generate_sample_data()
# Write the DataFrame to an Excel file with a specified sheet name
write_to_excel(df, "sample.xlsx", "Example1")
# Print the DataFrame to the console
print(df)
# Append the same DataFrame to the specified sheet in the Excel file
append_to_excel(df, "sample.xlsx", "Example1")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment