Read an Excel File from an S3 Bucket in Python
Many companies keep their master data files, such as holiday lists, price lists or employee lists, in an Amazon S3 bucket. A common task is to pick up such a file and load it into a database table, so the application can use it.
In this tutorial we connect Python to an S3 bucket, read an Excel sheet of public holidays straight from S3 (without saving it to disk), and insert the rows into a SQL Server table. The whole program is about 60 lines long. Every output on this page comes from a real run of the program with Python 3.14, boto3, pandas 3 and SQL Server.
Note: the bucket name and file name used on this page (my-company-master-files and India_Holidays.xlsx) are example names. Replace them with your own bucket and file.
What we will build
The program does seven small steps, one after another:
- Connect to AWS S3 with boto3.
- Download the Excel file from the bucket into memory.
- Read the Excel data with pandas.
- Connect to SQL Server with pyodbc.
- Insert each Excel row into the
Holidaytable, skipping rows that already exist. - Commit (save) the records.
- Close the connection.
The project has only three files:
PythonUpload/
├── requirements.txt # the Python libraries we need
├── create_table.sql # creates the database and tables in SQL Server
└── ReadLeaveFromS3.py # reads Excel from S3 and inserts into SQL Server
Prerequisites
- An AWS account with an S3 bucket, and an Excel file uploaded to it.
- Python 3 installed on your machine.
- SQL Server (Express or LocalDB is enough) and SQL Server Management Studio (SSMS).
- The Microsoft ODBC Driver 17 or 18 for SQL Server, which pyodbc uses to talk to SQL Server.
The Excel file has one sheet with four columns: HolidayId, HolidayName, Description and HolidayTypeId, and 12 rows of Indian public holidays.
Step 1: Create an IAM user for Python
Python needs AWS credentials to read from S3. Do not use your root account for this. Create a separate IAM user that is only allowed to read the files it needs:
- Sign in to the AWS Console and open IAM > Users > Create user.
- Give it a name, for example
python-s3-reader. It does not need console access. - Under Permissions, attach a policy that allows reading the bucket. For learning you can use the AWS managed policy
AmazonS3ReadOnlyAccess. For real projects, give access to only one bucket, as in the policy below. - Open the new user, go to Security credentials > Create access key, choose Command Line Interface (CLI), and copy the Access key ID and Secret access key. The secret is shown only once.
A policy that allows reading only the files in one bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::my-company-master-files",
"arn:aws:s3:::my-company-master-files/*"
]
}
]
}
s3:GetObject lets the program download a file; s3:ListBucket lets it list the folder, and also means that a wrong file name gives a clear "NoSuchKey" error instead of "Access Denied".
Step 2: Install the AWS CLI and run aws configure
The program below contains no access keys. Instead, we save the keys once on the machine with the AWS CLI, and boto3 finds them automatically. This keeps secrets out of your code and out of Git.
- Download and install the AWS CLI version 2 from the AWS website (on Windows it is an .msi installer).
- Open a new Command Prompt and check that it works:
aws --version
Now run aws configure and answer the four questions with the keys you copied in Step 1. The keys below are AWS's documented example values; type your own:
aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: ap-south-1
Default output format [None]: json
- Default region name is the region code of your bucket, for example
ap-south-1(Mumbai). You can see it in the S3 console next to the bucket name. - Default output format can be
json.
The AWS CLI saves the keys in C:\Users\<your user>\.aws\credentials and the region in C:\Users\<your user>\.aws\config. boto3 reads these same two files. Never commit or share the credentials file.
Check that your machine can see the file in the bucket:
aws s3 ls s3://my-company-master-files/Master-Files/Holidays/
If this command lists your file, the AWS side is ready. If it fails, fix it here first, because Python will fail with the same error.
Step 3: Create the database and table in SQL Server
Open SSMS and run create_table.sql. It creates a database LeaveDB and a Holiday table whose columns match the Excel file. The IF ... IS NULL checks make the script safe to run more than once: it only creates what is missing.
-- Run this in SQL Server Management Studio (SSMS) before running ReadLeaveFromS3.py
-- Safe to run more than once: it only creates what is missing.
IF DB_ID('LeaveDB') IS NULL
CREATE DATABASE LeaveDB;
GO
USE LeaveDB;
GO
IF OBJECT_ID('dbo.Leave', 'U') IS NULL
CREATE TABLE Leave
(
LeaveID INT PRIMARY KEY,
LeaveName VARCHAR(100),
LeaveDate DATE
);
GO
-- Matches the columns in India_Holidays.xlsx
IF OBJECT_ID('dbo.Holiday', 'U') IS NULL
CREATE TABLE Holiday
(
HolidayId INT PRIMARY KEY,
HolidayName VARCHAR(100),
Description VARCHAR(500),
HolidayTypeId INT
);
GO
HolidayId is the primary key, so the same holiday cannot be inserted twice. The Leave table is created for a later example and is not used by this program.
Step 4: Install the Python libraries
requirements.txt lists the four libraries the program uses:
boto3
pandas
openpyxl
pyodbc
| Library | Why we need it |
|---|---|
boto3 | The official AWS SDK for Python. We use it to download the file from S3. |
pandas | Reads the Excel data into a table-like DataFrame. |
openpyxl | The engine pandas uses to read .xlsx files. Without it, read_excel fails with "Missing optional dependency 'openpyxl'". |
pyodbc | Connects to SQL Server through the ODBC driver and runs SQL commands. |
Install them all with one command, from the project folder:
pip install -r requirements.txt
The versions used for this tutorial were boto3 1.44, pandas 3.0, openpyxl 3.1 and pyodbc 5.3. It is a good idea to create a virtual environment first (python -m venv .venv), so these libraries stay inside the project.
Step 5: The Python program, step by step
Here is the complete ReadLeaveFromS3.py. The sections below explain each step.
# ReadLeaveFromS3.py
# Read an Excel file from AWS S3 and insert its records into SQL Server.
#
# S3 URI: s3://my-company-master-files/Master-Files/Holidays/India_Holidays.xlsx
#
# AWS credentials are NOT set here. Run "aws configure" on your machine first.
import boto3
import pandas as pd
import pyodbc
from io import BytesIO
# STEP 1: CONNECT TO AWS S3
s3 = boto3.client("s3")
print("Connected to AWS S3")
# STEP 2: DOWNLOAD EXCEL FILE FROM S3
bucket_name = "my-company-master-files"
file_name = "Master-Files/Holidays/India_Holidays.xlsx"
response = s3.get_object(
Bucket=bucket_name,
Key=file_name
)
print("Excel file downloaded from S3")
# STEP 3: READ EXCEL FILE USING PANDAS
excel_data = response["Body"].read()
df = pd.read_excel(BytesIO(excel_data))
print("Excel Data:")
print(df)
# STEP 4: CONNECT TO SQL SERVER
conn = pyodbc.connect(
"DRIVER={ODBC Driver 17 for SQL Server};"
"SERVER=localhost\\SQLEXPRESS;"
"DATABASE=LeaveDB;"
"Trusted_Connection=yes;"
)
cursor = conn.cursor()
print("Connected to SQL Server")
# STEP 5: INSERT EXCEL RECORDS INTO SQL SERVER
# Rows whose HolidayId is already in the table are skipped,
# so the program can be run again without a duplicate key error.
inserted = 0
skipped = 0
for index, row in df.iterrows():
holiday_id = int(row["HolidayId"])
cursor.execute("SELECT 1 FROM Holiday WHERE HolidayId = ?", holiday_id)
if cursor.fetchone():
skipped += 1
continue
cursor.execute(
"""
INSERT INTO Holiday
(HolidayId, HolidayName, Description, HolidayTypeId)
VALUES (?, ?, ?, ?)
""",
holiday_id,
row["HolidayName"],
row["Description"],
int(row["HolidayTypeId"])
)
inserted += 1
# STEP 6: SAVE RECORDS
conn.commit()
print(f"Records inserted: {inserted}, already present (skipped): {skipped}")
# STEP 7: CLOSE CONNECTIONS
cursor.close()
conn.close()
print("SQL Server connection closed")
Step 1 in the code: connect to S3
boto3.client("s3") creates an S3 client. We do not pass any keys: boto3 looks for credentials in a fixed order (environment variables, then the ~/.aws/credentials file written by aws configure, then an IAM role when the code runs on AWS). The region comes from ~/.aws/config.
Creating the client does not contact AWS yet, so "Connected to AWS S3" only means the client object is ready. Wrong or missing keys are reported at the first real call, get_object.
Step 2 in the code: download the file
s3.get_object(Bucket=..., Key=...) downloads one file (S3 calls it an object). The key is the full path of the file inside the bucket, including the folders: Master-Files/Holidays/India_Holidays.xlsx. S3 has no real folders; the "folders" are just part of the key.
The response is a dictionary. Besides the file itself in response["Body"], it contains details about the file, such as its size and type. For our file:
Step 3 in the code: read the Excel data with pandas
response["Body"] is a stream. .read() gives us the raw bytes of the .xlsx file. pd.read_excel expects a file name or a file-like object, so we wrap the bytes in BytesIO, which makes them behave like a file that lives in memory. Nothing is saved to disk.
pandas reads the first sheet, uses the first row as column names and works out the type of every column:
If your file has several sheets, choose one with pd.read_excel(BytesIO(excel_data), sheet_name="Holidays").
Step 4 in the code: connect to SQL Server
pyodbc.connect takes a connection string with four parts:
- DRIVER: the ODBC driver installed on your machine. Run
python -c "import pyodbc; print(pyodbc.drivers())"to see the names you can use. - SERVER: your SQL Server instance name, as shown in the SSMS connect window. In a Python string the backslash must be doubled:
localhost\\SQLEXPRESS. - DATABASE: the database we created in Step 3.
- Trusted_Connection=yes: log in with your Windows account, so no password is needed in the code.
Steps 5 to 7 in the code: insert, commit and close
df.iterrows() goes through the DataFrame one row at a time. For every row, the program first checks whether that HolidayId is already in the table. If it is, the row is skipped; if not, it is inserted. Without this check, the second run of the program would stop with a primary key violation.
The ? marks are parameters. pyodbc sends the values separately from the SQL text, which protects against SQL injection and handles quotes in the data, such as the apostrophe in "India's independence". Never build the SQL with f-strings from file data.
int(...) converts the pandas number type (numpy.int64) into a normal Python int, which pyodbc can send to SQL Server.
pyodbc does not save changes automatically. The inserts are only stored when conn.commit() runs. If the program crashed halfway, nothing would be saved. Finally we close the cursor and the connection.
Step 6: Run the program
python ReadLeaveFromS3.py
All 12 rows were read from S3 and inserted. The ... in the middle is not missing data: pandas hides columns that do not fit in the console width. To print every column, add these two lines before print(df):
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 200)
Now run the same program a second time:
Every holiday is already in the table, so all 12 rows are skipped and no error occurs. When a new holiday is added to the Excel file in S3, only that new row will be inserted on the next run.
Step 7: Verify the data in SQL Server
Open SSMS and check the table:
USE LeaveDB;
SELECT * FROM Holiday ORDER BY HolidayId;
The 12 rows in SQL Server match the 12 rows of the Excel file in S3. The data, including the apostrophe in "India's", arrived unchanged.
Common errors and how to fix them
1. NoCredentialsError: Unable to locate credentials
boto3 found no access keys. Run aws configure (Step 2) as the same Windows user that runs the Python program, then open a new terminal.
2. NoSuchKey: The specified key does not exist
The bucket was found, but no file has that key. Keys are case-sensitive and must include every folder. Copy the key from the S3 console (Copy S3 URI) or from aws s3 ls, and remove the s3://bucket-name/ part. If the IAM user has no s3:ListBucket permission, S3 reports the same problem as AccessDenied instead.
3. Login failed for user / Cannot open database
S3 worked, but SQL Server refused the connection. Usually the database name is wrong or create_table.sql was not run yet, or the SERVER value does not match your instance name.
Interview questions
1. How do you read a file from S3 in Python without saving it to disk?
Call s3.get_object(Bucket=..., Key=...), read the bytes with response["Body"].read() and wrap them in io.BytesIO. Libraries like pandas can read from that in-memory file.
2. Where does boto3 get its credentials from?
From a chain of places, in order: parameters passed in code, environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY), the shared credentials file written by aws configure, and finally an IAM role when running on AWS (EC2, Lambda, ECS). Keys should not be written in the code.
3. What is the difference between boto3.client and boto3.resource?client is a low-level interface that maps one-to-one to the AWS API and returns dictionaries. resource is an older, object-oriented interface. AWS no longer adds new features to resources, so client is the recommended choice.
4. Why do we use ? parameters in pyodbc instead of f-strings?
Parameters keep data separate from the SQL command, which prevents SQL injection and correctly handles quotes and data types.
5. What happens if you forget conn.commit()?
pyodbc runs inside a transaction by default, so the inserts are rolled back when the connection closes and the table stays empty.
Summary
- Create an IAM user with read access to the bucket and save its keys with
aws configure; keep keys out of the code. - Install
boto3,pandas,openpyxlandpyodbcfromrequirements.txt. get_object+BytesIO+pd.read_excelreads an Excel file from S3 in memory.- Insert with
?parameters, skip rows that already exist, and callcommit()to save. - Verify the result with a
SELECTin SSMS.
Related tutorials: reading CSV and JSON files in Python, exception handling in Python, logging to a file and SQL Server, settings with .env files, read files from S3 in ASP.NET Core.