DEV Community

PDF4me
PDF4me

Posted on

How to Remove a Password From a Protected Excel File via API

How to Remove a Password From a Protected Excel File via API

Somebody in finance sends you a nightly export. It's encrypted, because of course it is, their IT policy requires it, and the password lives in a shared vault your automation already has access to. Your pipeline grabs the file, and then just sits there, because every downstream step you've built, reading rows, merging workbooks, extracting a worksheet, expects a plain, unprotected .xlsx. A password-protected file isn't a smaller version of the same problem. It's a different file format as far as your code is concerned, and the first thing any automation touching it has to do is take the lock off.

Why a protected workbook breaks more than you'd expect

Excel password protection isn't one setting. A workbook can be locked at the file level, so it needs a password just to open at all, at the workbook level, so nobody can add, delete, rename, or reorder sheets even after opening it, and at the worksheet level, so individual cells and formulas on a specific tab can't be edited. Those three locks are independent. A file can have all three, just one, or any combination, and a script that only knows how to strip file-open encryption will still choke on a workbook whose structure or worksheets are separately locked.

That's the actual shape of the problem PDF4me's Office API solves for Excel. It handles Word and Excel automation over HTTPS, no Microsoft Office installation required on either end, and the security side of that API covers both directions: locking a workbook down with Secure Excel, and reversing it with the operation this article is about, Unlock Excel.

What the Unlock Excel endpoint actually does

The Unlock Excel REST endpoint is a single POST to https://api.pdf4me.com/office/ApiV2Excel/ExcelUnlock, with Content-Type: application/json and a Basic Authorization header carrying your API key.

The request body has three parts: a document object naming the file (a Name field, like data.xlsx), a top-level docContent string holding the whole workbook as Base64, and an unlockExcelAction object holding the one field that actually matters, password, plus an optional cultureName for locale-sensitive processing. Here's what that looks like end to end in Python:

import base64
import os
import requests

API_KEY = os.environ["PDF4ME_API_KEY"]
EXCEL_PASSWORD = os.environ["EXCEL_PASSWORD"]  # never hardcode this

with open("data.xlsx", "rb") as f:
    doc_content = base64.b64encode(f.read()).decode("utf-8")

payload = {
    "document": {
        "Name": "data.xlsx"
    },
    "docContent": doc_content,
    "unlockExcelAction": {
        "password": EXCEL_PASSWORD,
        "cultureName": "en-US"
    }
}

response = requests.post(
    "https://api.pdf4me.com/office/ApiV2Excel/ExcelUnlock",
    json=payload,
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Basic {API_KEY}"
    }
)

result = response.json()

if not result.get("success", False):
    # Wrong password, or any other failure, lands here.
    # The file is returned untouched -- nothing partial happens.
    raise RuntimeError(result.get("errorMessage", "Unlock failed, no error message returned"))

unlocked_bytes = base64.b64decode(result["document"])
with open(result.get("fileName", "data_unlocked.xlsx"), "wb") as f:
    f.write(unlocked_bytes)
Enter fullscreen mode Exit fullscreen mode

The response hands back the unprotected workbook as a Base64 document, a fileName, a success flag, and an errorMessage that gets populated specifically when the password is wrong. That last point is worth sitting with for a second: this is explicitly described as requiring the correct password, not cracking one. Feed it the wrong password and you get success: false and an untouched source file back, not a brute-force attempt and not a partially unlocked result. If you don't have the password, this endpoint has nothing for you. That's a deliberate boundary, not a missing feature.

One password field on REST, three on every integration platform

Here's the detail worth knowing before you build on more than one surface, because it isn't obvious from the REST page alone. The REST endpoint takes exactly one password field, which only works cleanly if a workbook's file-open password, workbook-structure password, and worksheet password are all the same value, or if the file only has one of those three locks to begin with.

The Power Automate action, the Make module, and the Zapier action all expose three separate, independently optional password fields instead of one: a file-open password, a workbook-structure password, and a worksheet password. All three apply a fallback chain: supply just the file-open password, and each platform tries it against the workbook and worksheet locks too before giving up. That's a meaningfully more capable interface than the bare REST call for the common real-world case of a file where IT set one password for everything, but it also means a workbook locked with genuinely different passwords at each layer needs the right one supplied at the right layer, on every platform except REST, which simply can't express that case at all with a single field.

PDF4me's n8n node handles the same three layers slightly differently again: it keeps separate File Encryption and Workbook Protection password fields, but worksheet-level unlocking is a plain on/off toggle, "Unlock Worksheets," off by default, rather than its own password input. Three platforms, three different takes on the same three-layer lock. Worth confirming against your actual file before you assume any one platform's shape, especially if you're porting automation logic from one of these to another.

What this operation won't do, and its direct inverse

Unlock Excel is strictly a removal operation. It doesn't inspect a file to tell you which of the three lock types are present before you call it, it doesn't recover a forgotten password, and it doesn't touch anything else about the workbook: formulas, formatting, sheet contents, and cell values all come back exactly as they went in. If what you actually need is to add protection in the first place, not remove it, that's the separate Secure Excel endpoint, which takes the inverse set of options: a password, a protectWorkbook flag, a protectWorksheets flag with a worksheetProtectionType of Contents, Objects, Scenarios, or All, and independent fallback passwords for each layer, mirroring the same three-lock model Unlock Excel removes. If your pipeline both receives protected files from one system and needs to re-protect its own output before handing it to another, you're looking at these two endpoints as a matched pair, not two unrelated features.

Which surface to build this on

None of the four integration platforms change what comes back, only how much control you get over which password goes where, so the choice mostly comes down to where the protected file already lands. If it arrives through a shared mailbox, a SharePoint library, or anywhere else already inside Microsoft 365, Power Automate keeps the whole unlock step inside that ecosystem without adding a second tool to maintain. Make's own documentation describes pulling the file in as binary content mapped from a prior step, such as a cloud-storage download, which fits a scenario where the protected workbook is already sitting in Drive, Dropbox, or an FTP drop before your scenario ever touches it. Zapier is the natural fit when the protected file is already the output of an earlier Zap step, a form upload or an inbox attachment parser, since the Unlock action just slots in as the next step with nothing extra to configure. n8n suits teams already running self-hosted or hybrid automation who want the unlock step living in the same workflow as everything else, including, in this one case, a plain on/off switch for the worksheet layer instead of a password field to fill in. REST is the fit when you want the logic living in your own codebase instead of a third-party automation platform, as in the Python example above.

A realistic version of this: the nightly encrypted export

Picture a payroll or banking integration that drops a password-protected .xlsx into a monitored folder every night, the password itself stored once in a secrets manager rather than typed by a human each time. A workflow built on Power Automate, Make, Zapier, n8n, or a scheduled script like the one above picks the file up on arrival, pulls the password from that secrets store, and runs the Unlock action before anything else touches the file. Every step after that, extracting specific rows, merging the sheet into a master report, reading values into a database, operates on a workbook that's never been manually opened by a person at all. The lock that used to mean "someone has to open this by hand first" becomes a single step at the front of the pipeline instead, and because a wrong password fails loudly with errorMessage populated rather than silently returning garbage, a bad credential in the secrets store gets caught the same night, not three reports downstream.

Where to go from here

If you're calling this directly, start with the REST API reference, and remember that it assumes one password covers every lock on the file. If you're building inside a no-code tool and need to handle a file-open password that differs from its workbook or worksheet passwords, the Power Automate, Make, Zapier, and n8n actions give you that flexibility, each with its own small variation on how the worksheet layer is addressed. And if your workflow needs to protect a file before Unlock Excel ever needs to touch it again, Secure Excel is the other half of that pair. Either way, what used to require a person with the password sitting at a keyboard becomes one HTTP call that either returns a clean, workable file or tells you plainly, and immediately, that the password was wrong.

Website: pdf4me.com
Documentation: docs.pdf4me.com

Top comments (0)