Back to blog

Extract Data from API to Excel: Steps That Hold Up

Learn how to extract data from API to Excel with Power Query, covering authentication, pagination, validation and safe refreshes for finance and ops teams.

Extract Data from API to Excel: Steps That Hold Up

The first business day of the month. An analyst opens the reporting workbook, clicks Refresh All, and watches the status bar sit on "Running query" for forty seconds before a clean table of a thousand rows appears. The finance review goes ahead. Nobody notices the API returned a second page the query never requested.

That gap is where API-to-Excel work usually fails, and it fails without warning. The mechanics aren't the hard part: a web connection, a parsed JSON response, a loaded table. What breaks in production sits around the edges, in a token that expired, a second page nobody requested, a currency column that arrived as text, a refresh that overwrote last week's evidence.

Getting values into cells is a fifteen-minute job. Building a workbook someone can defend in an audit is a different exercise, and it's the one worth reading about.

How to Pull API Data into Excel with Power Query

Excel can call an API without a line of code. The engine is Power Query, the Get and Transform layer that lives on the Data tab. Microsoft shipped it in Excel 2010 for Windows as a free add-in, folded it into the ribbon as "Get & Transform Data", and deprecated the standalone add-in in early summer 2019 for Excel 2010 and 2013, according to Microsoft's Power Query overview. The same documentation notes the feature has been supported on Windows for more than ten years and now runs on Windows, Mac and the web, and that in 2025 Excel for the Web added refresh support for queries connected to authenticated sources.

That last detail changes what a workbook is for. A query that refreshes against a protected endpoint is a recurring interface, not a one-off export. If you also pull structured records from other providers, the on-chain data guide for quant builders is a useful look at how request shape determines response shape, and the lesson transfers to any endpoint you point Excel at.

The sequence below produces a table you can trust.

  1. Open the connection with the exact request. Data > Get Data > From Web, then paste the full endpoint including parameters such as page size and output format. The connector sends exactly what you give it, so a missing parameter returns a different field set. The common slip is testing with the URL from a browser address bar that dropped the format parameter.

  2. Choose the authentication method, then connect. Pick the wrong one and you get a 401 or an empty table, never a helpful error.

  3. Convert the response into a table, then expand the record list into rows. Use To Table on the returned record or list, then the expand icon in the column header to choose fields. If every cell in a column reads "Record" or "List", you stopped one expand too early.

  4. Set data types before loading. Dates, decimals, currencies and identifiers need explicit types inside Power Query, because automatic inference turns a leading-zero invoice number into a number and can misread decimal separators. Typing early is cheaper than auditing later.

  5. Close and Load, sending large results to the Data Model. A few hundred thousand rows belong in Power Pivot rather than a sheet.

  6. Run Refresh All. This is the key test, not the first load. If it prompts for credentials again or reports a missing column, the query isn't finished.

A four-step infographic explaining how to import API data into Microsoft Excel using Power Query.

What a healthy result looks like. One row per record. Column headers that match the JSON field names you expanded. A row count you can compare against the total the API reports for that filter. When those three hold, extract data from API to Excel is done, and everything that follows is about keeping it true next month.

Choose the Authentication Method Your API Needs

The wrong authentication choice is the most common reason a first connection fails. The symptoms differ: a 401 Unauthorized, a table with headers and no rows, or a refresh that demands a sign-in every morning. All three trace back to the method selected in the From Web dialog.

Microsoft's Power Query Web connector documentation lists seven methods the connector supports. Matching your API's scheme to the right row takes a minute.

Method Typical use What to enter in Excel
Anonymous Public endpoints that need no key Nothing; the URL is enough
Basic Username and password over HTTPS Username and password
Web API API key or token sent in a header Key value and the header name the API expects
Windows Internal services that accept a Windows login Current Windows credentials
Organizational Account Services protected by a Microsoft work account Sign in with the work account
Service Principal Unattended, app-level refreshes Tenant ID, client ID and client secret
Browser-based Sites that show a login page Sign in inside the Excel prompt window

Three rules that prevent most failures

Store credentials in Data Source Settings, never in a cell. A key pasted into column A travels with every copy of the file, including the one someone emails on a Friday. Data > Get Data > Data Source Settings is where a credential belongs.

Use Service Principal only for unattended refresh. It needs a tenant ID, a client ID and a secret, which means somebody owns rotation. That's the right trade for a scheduled job and the wrong one for an analyst testing an endpoint.

Send one small request before pulling a full dataset. Set the page size to 10, confirm the fields, then scale up. Debugging a ten-row response takes minutes; debugging a timeout on a full dataset takes an afternoon.

Public sector APIs show how far a well-formed request can go. Eurostat documents a Power Query expression using Web.Contents against its API endpoint, with a request over 100 characters that sets format, version and compression. Its guidance recommends CSV or TSV output because those load directly as web data, and notes that its JSON-STAT format is built for web visualization and has no native Excel toolkit. When Excel is the destination, ask the provider for tabular output.

The same discipline governs commercial feeds, where secure authentication for real estate APIs treats token scope and expiry as design decisions rather than setup details. If you're mapping the wider integration, the guide to API integration best practices covers the parts that sit outside the workbook.

The check is concrete. The Navigator window previews rows without an error, and Refresh All completes without a new sign-in prompt.

Pull Every Page and Handle Throttling Safely

A workbook that imports only the first page looks perfect. Headers are right, types are set, formulas calculate. It is also missing most of the data, and nothing in Excel will tell you. Pagination is a data-integrity problem before it is a performance problem, as Microsoft's paging sample for Power Query makes clear: the documented pattern checks the outer response for an odata.nextLink value, requests that URL, and combines pages with a reusable Table.GenerateByPage() function.

Identify the pagination style before writing a loop

Pagination style How to recognise it Loop stops when Store between requests
OData nextLink Response includes an odata.nextLink value No nextLink is returned The last nextLink URL
Offset and limit Parameters named offset, skip or page size A page returns fewer rows than the limit The last offset and the running total
Cursor Response returns a next cursor or token The cursor is empty or null The last cursor value
Page number A page parameter increases by one each request An empty page or a page past the total The last page number and the count

Stop rule: a page that returns fewer rows than you requested is the last page. Every other stopping condition is a guess.

For offset pagination, add the returned page size to the offset on each pass and compare rows received against the limit. For cursor APIs, persist the server-issued cursor exactly as returned and never derive an offset from a row count, because the underlying data shifts between requests. Cursor values are opaque strings, so store them as text with no type conversion. A number-formatted cursor loses digits and the next request fails.

Normalize nested data before it lands

Order lines inside an invoice response should become a child table keyed by invoice ID, not parent fields repeated across forty rows, because duplicated parent fields multiply the moment someone sums a total. Expand arrays into their own query, keep stable source identifiers on both tables, and type dates, decimals, currencies and nulls explicitly. Excel's inference will happily turn a null into a zero and a three-letter currency code into a date.

Handle each response with one action

OWASP's API testing guide recommends server-side maximum page sizes, bounded bulk requests, per-client rate limits and rate-limit headers such as RateLimit or X-RateLimit-Remaining, and names unbounded pagination as both a resource-exhaustion and a data-exfiltration risk. Read those headers on every response and slow down before you're refused.

  1. 429 means you were rate limited. Wait, then retry with exponential backoff plus jitter so parallel refreshes don't collide on the same second. Retrying immediately turns a short pause into a longer block.
  2. 502 or 503 means a temporary failure upstream. Retry with backoff, then resume from the last checkpoint instead of restarting the run.
  3. A failed POST may or may not have created a record. Retry only when the API accepts an idempotency key, otherwise a duplicate document lands in finance with no error anywhere.

Checkpoint the last successful cursor or offset after every page, in a parameters table or a named cell. A failed run then resumes from that point rather than pulling page one again.

What to test before release

Test three pages, not one. Test an empty page, a duplicated record, an expired token and a malformed JSON body. Send a dataset larger than Excel can hold: worksheets support 1,048,576 rows by 16,384 columns, so a bigger extract belongs in the Data Model or split across tables. Treat row-count reconciliation, duplicate-ID detection and mandatory-field validation as release gates. A refresh that returns 200 OK with half the rows is worse than an error, because nobody investigates it.

A run that fails midway should leave the previous sheet untouched and log the reason on an audit tab. Half-written tables are how a report blends yesterday's figures with today's.

Check Types, Duplicates and Row Counts Before Anyone Uses the Sheet

Wrong data has a price. A European study found that incorrect information caused payment delays for 15.1% of invoices transacted in Europe, according to the European Commission's analysis of e-invoicing benefits. The same analysis puts the cost reduction from electronic invoicing at 54.5% for issuers and 71.8% for receivers compared with paper processing. Most of that value depends on fields being right before approval, not on the format they arrive in.

Run these checks on every refresh, not once at build time.

  • Mandatory fields present: invoice number, supplier tax ID, total and currency. A blank row should fail loudly rather than pass unnoticed.
  • Source ID unique: count distinct IDs against row count. A duplicate nobody flags gets summed twice.
  • Row count equals the API total: the number the endpoint reports for the same filter is the only external check you have.
  • Totals reconcile: line items should sum to the header total within your rounding tolerance.
  • Numbers stored as numbers: a SUM returning 0 almost always means a currency or amount column arrived as text.
  • Dates match a known record: convert time zones once, at the boundary, and confirm against one record you can verify by hand.
  • Decimal separator matches the regional setting: a comma-decimal export read under a point-decimal locale shifts values by orders of magnitude.
  • Nulls stay separate from zero: a missing discount and a zero discount are different facts about the same invoice.

A case that repeats across invoice exports: the currency column arrives as text, the amount column arrives as text beside it, and the monthly total reads 0 for three weeks because the SUM skipped every row. The fix is a type change in Power Query, which takes a click and eliminates the entire class of error.

Add a validation column beside the data. A formula returning "OK" or the failing rule name per row lets a reviewer filter exceptions instead of rereading four thousand lines. If you're standardising those rules across several workbooks, these notes on data validation rules in Excel cover the patterns that survive a schema change.

The release rule is simple: no workbook goes to finance until the row count, the total reconciliation and the duplicate check all pass on a fresh refresh.

Keep an Audit Trail Excel Can Defend

A refresh that overwrites yesterday's values destroys the evidence that anyone reviewed them. Research into spreadsheet risk in multi-user environments identifies unauthorised access and modification as recurring causes of errors with financial and reputational consequences, and an analysis of documented failures attributes 71 cases to formula errors, data-entry slips and data-handling mistakes, per the study on spreadsheet failure modes. Automation removes the manual copying without removing the governance problem.

A laptop displays a spreadsheet showing automated API data synchronization of customer orders with JSON payloads.

The fields that make a row reviewable

Keep these beside every row rather than inside a summary tab: the raw API payload, the source document ID, the extraction timestamp, the schema or model version, a confidence score where the API returns one, and a validation status. With those six, a reviewer reconstructs any value without leaving the workbook.

Since a refresh can legitimately return nothing for a field, use an explicit status column with three values: returned no value, extraction failed, intentionally blank. Collapsing them into an empty cell is the most expensive shortcut in the file.

Corrections belong in a new versioned row. Overwriting the original value deletes the only record of what changed and who changed it.

Protect formulas, restrict edit rights by role, and reconcile against source totals each period. If a document extraction provider sits upstream, check its security posture against your own requirements: Matil, for example, operates under GDPR, holds ISO 27001 and AICPA SOC certification, applies zero data retention, and processes client data on AWS in the London region, Google Cloud Platform in Europe, and OpenAI models under enterprise privacy clauses. Processing location is a compliance question, not a procurement detail.

If your review process has to survive an external audit, these notes on traceability requirements set out what an auditor will ask for.

Three questions a reviewer should answer from the workbook alone: where did this value come from, when was it extracted, and what changed since the last version. If any answer needs an email to the person who built the query, the trail isn't there yet.

Decide Whether Excel Should Be Your Extraction Layer

Excel is a good review and reporting layer and a poor extraction engine. That verdict holds whenever volumes are large, the API requires an OAuth flow, or the refresh has to run unattended at 2 a.m. Microsoft's guidance on external calls from Office Scripts draws the boundary: Office Scripts can't perform OAuth-based authentication flows, external calls normally run through the Excel application rather than Power Automate, requests and responses are capped at 5 MB, worksheet ranges at five million cells, and payloads should be paginated because pulling a whole dataset in one request is impractical.

The pressure to get this right is coming from the data side. Postman's 2025 State of the API report found that 82% of organizations surveyed worldwide had adopted an API-first approach to some degree, with 25% operating as fully API-first. Excel is usually the last stop on that chain, not the first.

Option Best for Main risk Example fit
Direct Power Query refresh One team, small and mostly static datasets Silent partial pages and no audit trail Monthly report from a public endpoint
Office Scripts with Power Automate Scheduled updates from APIs without OAuth Request size limits and external-call failures Daily summary from a simple, open API
Scheduled middleware job Protected APIs, large or changing datasets Maintaining token storage, retries and logs Nightly ERP export into a database, then Excel for review
Document extraction API such as Matil.ai Invoices, payslips, KYC files and bills of lading Setting up field mapping and validation rules Turning PDF invoices into structured rows for Excel

Rule of thumb: if the refresh needs a person to click it, Excel can be the layer. If it has to run without one, build upstream.

A comparison chart deciding between using Excel or upstream extraction for processing and managing extracted data.

Where document extraction fits

Invoices, payslips, identity documents and bills of lading aren't API responses at all. They arrive as PDFs and photos, and the first job is turning them into structured JSON that Power Query or Office Scripts can consume. That's the layer Matil.ai covers: OCR, classification, validation and workflow orchestration behind one API, with three processing modes. Normal returns structured data synchronously for real-time integrations. Async accepts a document and delivers results by webhook when ready. Batch takes hundreds of documents in a single request, which suits nightly imports and migrations. Matil also fills the Excel and PDF templates you define with the extracted values, so the workbook keeps the layout finance already knows. Reported accuracy sits above 99% across several use cases, and the test that matters is still your own documents.

If you're weighing scraping against a documented endpoint for the sourcing step, this data sourcing guide for founders sets out the trade-offs.

The pilot that settles the argument

Four steps, in order. Count documents per month, because a small monthly batch and a heavy one need different architectures. Decide whether the refresh is interactive or scheduled. Write down the audit requirements before you watch a demo. Then pilot on about 100 documents and reconcile totals against manual entry, line by line, with the same reviewer who will own the output.

If the pilot's error rate isn't clearly lower than manual entry, the problem isn't the tool. It's the field definition, and no amount of automation fixes an ambiguous schema.


Matil turns invoices, payslips, KYC files and bills of lading into structured JSON that Power Query or Office Scripts can pull straight into your workbook, and fills the Excel templates you already use so the layout stays intact. One API covers synchronous checks, webhook delivery and batch imports, which means the same integration serves a real-time validation and a nightly run. If you're evaluating this step, visit Matil to see how the API fits the workflow you have today.

Related articles

© 2026 Matil