Automate Boring Office Tasks with ChatGPT and Python
Six office jobs handed to ChatGPT-written Python: distributing Excel files through Outlook, building a PowerPoint deck, an interactive chart, merging PDFs, drafting an email and a small Streamlit website. The pattern repeats each time: describe the task precisely, name the library you want, and read the code before you run it.
Table of contents
Email Excel files with Outlook
The first script reads a list of recipients from the Email_List sheet of Financial_Data.xlsx and creates one Outlook email per row, each with its own attachment, recipient and CC. It opens the drafts for review instead of sending them.
The sheet has four columns. Column A holds the attachment file name, which the code looks up in a folder called Attachments. Column B is the recipient’s name for the greeting, column C the email address and column D the CC address. ChatGPT showed a content policy warning on this prompt but still wrote the code.
The first version ran and created a correct draft for each country, with one deprecation warning. I pasted the warning back into ChatGPT and the second version ran clean. Replace mail.Display() with mail.Send() once you trust the output. I built the same Outlook job by hand in creating and emailing Excel files with Python and Outlook, if you want to compare the two scripts.
import os
import openpyxl
import win32com.client as win32
# Get the current working directory
cwd = os.getcwd()
# Load the Excel workbook
workbook = openpyxl.load_workbook(os.path.join(cwd, "Financial_Data.xlsx"))
# Select the sheet
sheet = workbook["Email_List"]
# Get the Outlook application object
outlook = win32.Dispatch('outlook.application')
# Iterate through the rows in the sheet
for i in range(2, sheet.max_row + 1):
# Get the attachment file name
attachment = sheet.cell(row=i, column=1).value
attachment_path = os.path.join(cwd, "Attachments", attachment)
if not os.path.exists(attachment_path):
print(f"Attachment {attachment} does not exist")
continue
# Get the recipient name
recipient_name = sheet.cell(row=i, column=2).value
# Get the recipient email address
recipient_email = sheet.cell(row=i, column=3).value
# Get the CC email address
cc_email = sheet.cell(row=i, column=4).value
# Create a new email
mail = outlook.CreateItem(0)
# Set the recipient and CC email addresses
mail.To = recipient_email
mail.CC = cc_email
# Set the email subject
mail.Subject = f"Financial Data: {attachment}"
# Set the email text
mail.Body = f"Dear {recipient_name},\n\nPlease find the attached financial data for {attachment}.\n\nBest regards,\nYour Name"
# Add the attachment
mail.Attachments.Add(attachment_path)
# Open the email in Outlook
mail.Display()
# close all opened objects
workbook.close()
Build a PowerPoint deck
The second script reads every Excel file in an input folder, drops rows with missing values, sums sales by product, saves one Seaborn bar chart per file in a charts folder and puts each chart on its own titled slide in a new PowerPoint file.
Name the library in the prompt. I asked for Seaborn; without that, ChatGPT may pick another one such as Matplotlib. The deck it produced is plain, but it is a working starting point you can style later.
ChatGPT’s first version showed a FutureWarning, and that warning came true: since pandas 2.0, df.groupby('Product').sum() fails on these files because they contain text and date columns. The version below selects the Sales column before summing, which gives the same totals. If you would rather send existing Excel charts and tables to PowerPoint without writing code, my Excel2PPT add-in does that in one export.
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from pptx import Presentation
from pptx.util import Inches
# Determine the directory of the script
script_dir = os.path.dirname(os.path.abspath(__file__))
input_folder = os.path.join(script_dir, 'input')
charts_folder = os.path.join(script_dir, 'charts')
ppt_file = 'financial_data.pptx'
# Create the charts folder if it doesn't exist
if not os.path.exists(charts_folder):
os.mkdir(charts_folder)
# Create a new PowerPoint presentation
prs = Presentation()
# Iterate through all Excel files in the input folder
for excel_file in os.listdir(input_folder):
if not excel_file.endswith('.xlsx'):
continue
# Read the financial data from the first worksheet of the Excel file
file_path = os.path.join(input_folder, excel_file)
df = pd.read_excel(file_path, sheet_name=0, usecols="A:P")
df = df.dropna()
# Group the data by the "Product" column and sum up the "Sales" column
grouped = df.groupby('Product')['Sales'].sum()
# Create a chart using the seaborn library
sns.barplot(x=grouped.index, y=grouped.values)
plt.title(excel_file)
plt.xlabel('Product')
plt.ylabel('Sales')
plt.tight_layout()
# Save the chart to the charts folder
chart_file = excel_file.replace('.xlsx', '.png')
chart_path = os.path.join(charts_folder, chart_file)
plt.savefig(chart_path)
# Add a slide to the PowerPoint presentation and insert the chart and title
slide = prs.slides.add_slide(prs.slide_layouts[5])
title = slide.shapes.title
title.text = excel_file.replace('.xlsx','')
chart_file = chart_path
left = Inches(0.5)
top = Inches(1)
width = Inches(9)
height = Inches(6)
slide.shapes.add_picture(chart_file, left, top, width=width, height=height)
# Save the PowerPoint presentation in the same directory as the script
ppt_path = os.path.join(script_dir, ppt_file)
prs.save(ppt_path)
Interactive Plotly chart
The third script sums sales per country from the Data sheet and saves an interactive Plotly bar chart as an HTML file. I gave the bar color as a hex code in the prompt, and the script checks that the Country and Sales columns exist before it plots.
import pandas as pd
import plotly.express as px
import os
try:
# load the data from the "Data" sheet of the "Financial_Data.xlsx" workbook
data = pd.read_excel("Financial_Data.xlsx", sheet_name="Data")
# check if 'Country' and 'Sales' columns exists in data
if 'Country' not in data.columns or 'Sales' not in data.columns:
raise ValueError("Columns are missing")
# group the data by country and calculate the total sales for each country
sales_by_country = data.groupby("Country")["Sales"].sum().reset_index()
# create the bar chart
fig = px.bar(sales_by_country, x="Country", y="Sales", title="Financial Data By Country",
labels={"Country": "Country", "Sales": "Total Sales"},
color_discrete_sequence=["#00008B"])
# save the chart to the same directory as the workbook
fig.write_html("Financial Data By Country.html")
# display the chart
fig.show()
except FileNotFoundError as e:
print(f"{e} not found")
except ValueError as e:
print(e)

Merge PDFs
A subscriber had two folders, cover and draft. Each numbered PDF in the cover folder belongs in front of the draft PDF with the same number. The goal was one merged file per pair, cover first.

I gave ChatGPT a concrete example of how the files match. The first answer failed with an error; I pasted the error back and the second version ran and wrote the merged files to an output folder.
The first answer imported PdfFileMerger, a class newer PyPDF2 releases no longer support. PyPDF2 itself is no longer maintained; its successor is pypdf, where PdfWriter has an append() method for the same job. A similar real request, merging files that share the start of their name, is explained step by step in merging PDF files by name with Python.

Draft an email
ChatGPT also writes the text around the work. As a half-serious test I asked for an email to my manager requesting a raise, and it built the argument on the automations above. Treat it as a first draft to edit, not a message to send as is.

Streamlit website
The last example is a small Streamlit website, also written with ChatGPT, that lists every prompt from this post with its chat history. Its code is in the 06_Create_Website folder of the GitHub repository below.
For five more Excel-only examples with their prompts, see Excel automation with ChatGPT and Python.
