Fixing 'Getting Bad Zip File' Error When Reading Excel File from SharePoint Online using Python in Jupyter Notebook

Abstract: Resolve BadZipFile errors when reading Excel files from SharePoint Online in Python by using msal to obtain OAuth2 tokens for authenticated requests.

Created: 2026-09-30 by

The 'Bad Zip File' error when reading Excel from SharePoint Online in Python usually stems from receiving an HTML login redirect instead of the binary file content. This happens because requests or urllib does not automatically handle SharePoint's authentication flow, causing the downloaded stream to be invalid for libraries like openpyxl or pandas. Using proper OAuth2 tokens via msal ensures the request returns actual file data.

Understanding the Root Cause

When you attempt to download a file from SharePoint Online using standard HTTP clients, you often encounter this error not because the file is corrupted, but because the server responds with a 302 Redirect to the Microsoft login page. Libraries such as pandas or openpyxl expect a valid ZIP archive (which is what .xlsx files are). When they receive HTML markup containing the Microsoft Sign-In form, they fail to parse it as a zip structure, raising the BadZipFile exception. This issue is distinct from formatting errors seen in local Excel files. For instance, if you were dealing with calculation issues, you might look into Solving Filter Function SumIFS <> 0 Error. However, in this case, the problem is purely at the transport layer: the data never reaches your script correctly due to authentication failures. Standard basic authentication is deprecated and unsupported by modern SharePoint Online environments, making token-based approaches mandatory.

Prerequisites and Setup

To resolve this, you must switch from simple URL fetching to authenticated requests. You will need the following Python packages installed in your Jupyter environment:
  • msal: Microsoft Authentication Library for obtaining access tokens.
  • requests: To send the authenticated HTTP GET request.
  • pandas or openpyxl: For reading the Excel file once retrieved.
  • io.BytesIO: To handle the binary stream in memory.
You also need Azure Active Directory (Entra ID) permissions. Register an application in the Azure Portal, grant it Files.Read or Files.ReadWrite.All permissions for Microsoft Graph, and note down your Client ID, Tenant ID, and Client Secret.

Step-by-Step Solution

The core strategy involves acquiring an OAuth2 token and attaching it to the request headers. Here is how to implement this securely in Jupyter Notebook.

1. Acquire the Access Token

Use the msal library to obtain a token for the Microsoft Graph API. The scope should be set to https://graph.microsoft.com/.default.
import msal
import requests

client_id = "YOUR_CLIENT_ID"
tenant_id = "YOUR_TENANT_ID"
client_secret = "YOUR_CLIENT_SECRET"
authority = f"https://login.microsoftonline.com/{tenant_id}"

app = msal.ConfidentialClientApplication(
    client_id,
    authority=authority,
    client_credential=client_secret
)

result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
access_token = result.get("access_token")

if not access_token:
    raise Exception("Failed to acquire token", result.get("error_description"))

2. Construct the SharePoint Download URL

SharePoint Online exposes files through the Microsoft Graph API. Instead of using the direct SharePoint URL which triggers redirects, use the Graph endpoint. Replace {site-id}, {item-id} with the specific identifiers of your document library item.
# Example using Graph API for a specific file
file_url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/lists/{list_id}/items/{item_id}/driveItem/content"

headers = {
    "Authorization": f"Bearer {access_token}",
    "Accept": "application/octet-stream"
}
Alternatively, if you have the direct URL to the file in SharePoint, you can still use it, but you must ensure the header is present. The key is that the request must include the Bearer token.

3. Download and Read the File

Make the GET request and check the status code. If it is 200 OK, the content is binary. Load it directly into pandas without saving to disk first, which is efficient for Jupyter Notebooks.
response = requests.get(file_url, headers=headers)

if response.status_code == 200:
    import pandas as pd
    from io import BytesIO
    
    # Load the binary content into a BytesIO object
    excel_file = BytesIO(response.content)
    
    # Read the Excel file
    df = pd.read_excel(excel_file, engine='openpyxl')
    print(df.head())
else:
    raise Exception(f"Failed to download file: {response.status_code} {response.text}")
By ensuring the Authorization header is present, you bypass the login redirect. The server recognizes the token and serves the actual ZIP content of the Excel file.

Common Pitfalls

Ensure that your Azure App Registration has the correct permissions enabled and that consent has been granted by a global administrator. Without consent, the token acquisition might succeed, but the subsequent API call will return a 403 Forbidden or a redirect to an error page, which still causes parsing failures. Also, verify that the site_id and item_id are correct. You can find these by navigating to the file in SharePoint, clicking "Copy link," and extracting the IDs from the URL structure, or by using the Graph Explorer tool. For related data validation issues, you might explore Resolving '#NAME' Error in XLOOKUP, though that pertains to formula logic rather than data retrieval.

Security Best Practices

Never hardcode client secrets in your Jupyter notebooks. Use environment variables or Azure Key Vault to store sensitive credentials. In production scripts, consider using Managed Identities if running on Azure services, which eliminates the need for client secrets entirely. Always validate the response content type before attempting to parse it as Excel, ensuring it is indeed application/vnd.openxmlformats-officedocument.spreadsheetml.sheet or similar.

Frequently Asked Questions

Why do I get a 403 Forbidden error after fixing the Bad Zip File error?

A 403 error indicates that while your authentication is working, your application lacks permission to access the specific file or site. Check the Azure Portal to ensure the Files.Read permission is granted and that tenant admin consent has been applied to your registered app.

Can I use basic authentication with SharePoint Online?

No, Microsoft has disabled basic authentication for SharePoint Online and OneDrive for Business. Attempting to use username and password pairs will result in authentication failures or redirects to MFA prompts, which cannot be handled programmatically in standard Python requests.

How do I find the Site ID and Item ID for my Excel file?

You can retrieve these IDs using the Microsoft Graph Explorer. Navigate to the file in your browser, copy the link, and parse the URL, or use the /sites/root/lists/{list-id}/items endpoint to list items and identify the correct ID for your target file.

What if the Excel file is too large to load into memory?

If the file exceeds available RAM, save the binary content to a temporary file on disk using with open('temp.xlsx', 'wb') as f: f.write(response.content), then pass the file path to pandas.read_excel() instead of using BytesIO.

Does this method work for OneDrive personal accounts?

This approach is designed for SharePoint Online and OneDrive for Business within an organization. For personal OneDrive accounts, you would typically use the Microsoft Personal Graph API or OAuth flows tailored for consumer accounts, which differ slightly in scope and token endpoints.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More