AI News
  • Home
  • Artificial Intelligence
  • E-commerce
  • News
  • Featured
  • Web World
  • Contact
No Result
View All Result
AI News
  • Home
  • Artificial Intelligence
  • E-commerce
  • News
  • Featured
  • Web World
  • Contact
No Result
View All Result
AI News
No Result
View All Result

Export WooCommerce Orders to CSV with Python

Paul H by Paul H
July 25, 2026
in WordPress
4 1
0
Python script exporting WooCommerce orders to CSV file
6
SHARES
Summarize with ChatGPTShare to Facebook

If you’ve ever tried to export WooCommerce orders with their line items into a flat CSV, you know the pain: WooCommerce’s REST API nests line items inside each order object. One order might have five products, but you need each product on its own row, with the order number, customer, and totals repeated. Doing this manually is error-prone. Python can automate the entire job in under 50 lines of code.

This guide walks you through the complete process — from creating API credentials to saving a clean, Excel-friendly CSV with one row per purchased item.

Prerequisites

Before you start, make sure you have:

  • A WooCommerce store (version 3.5 or later recommended).
  • Python 3.7+ installed on your machine.
  • The requests library installed (pip install requests).
Prerequisites — illustration for Export WooCommerce Orders to CSV with Python

You’ll also need REST API credentials from your WooCommerce store. Here’s how to get them:

  1. Go to WooCommerce > Settings > Advanced > REST API.
  2. Click Add Key.
  3. Give it a description like “CSV Export Script”.
  4. Choose Read permissions (you only need read access for exporting).
  5. Click Generate API Key.
  6. Copy the Consumer Key and Consumer Secret.

Store these securely — they grant access to your store data.

Step 1: Set Up Authentication and Fetch Orders

WooCommerce uses OAuth 1.0a for REST API authentication. The woocommerce Python package handles the signing, but you can also use raw requests with oauthlib. For simplicity, we’ll use the woocommerce package:

Step 1: Set Up Authentication and Fetch Orders — illustration for Export WooCommerce Orders to CSV with Python
bash
pip install woocommerce

Now, create a Python script (e.g., export_orders.py) and initialize the API client:

python
from woocommerce import API

wcapi = API(
    url="https://yourstore.com",  # Replace with your store URL
    consumer_key="ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    consumer_secret="cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    version="wc/v3"
)

Why v3? WooCommerce v3 API is the most stable and supports all features. It’s widely used as of 2026.

Step 2: Download Orders with Nested Line Items

The API returns orders with a line_items array. Each item contains name, quantity, price, total, tax, and sku. But the API limits results to 100 orders per page (default). We need pagination.

Step 2: Download Orders with Nested Line Items — illustration for Export WooCommerce Orders to CSV with Python

Let’s fetch the first page:

python
orders = wcapi.get("orders", params={"per_page": 100, "page": 1}).json()

Check if the request succeeded:

python
if not orders:
    print("No orders found or API error.")
    exit()

Step 3: Expand Line Items into Separate Rows

For each order, iterate over its line items and create one row per item, repeating the order-level fields (order ID, customer name, etc.).

Step 3: Expand Line Items into Separate Rows — illustration for Export WooCommerce Orders to CSV with Python

We’ll build a list of dictionaries, then use csv.DictWriter to write the file.

python
import csv

rows = []
for order in orders:
    order_id = order['id']
    customer_name = f"{order['billing']['first_name']} {order['billing']['last_name']}"
    for item in order['line_items']:
        rows.append({
            'Order ID': order_id,
            'Customer': customer_name,
            'SKU': item.get('sku', ''),
            'Product': item['name'],
            'Quantity': item['quantity'],
            'Total': item['total']
        })

# Write to CSV
with open('orders.csv', 'w', newline='', encoding='utf-8-sig') as f:
    fieldnames = ['Order ID', 'Customer', 'SKU', 'Product', 'Quantity', 'Total']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)

print(f"Exported {len(rows)} line items.")

Why utf-8-sig? Excel on Windows expects a BOM to correctly interpret UTF‑8. Without it, special characters (e.g., é, ü) may appear garbled.

Step 4: Handle Pagination for Large Stores

If you have more than 100 orders, you need to loop through pages. The API response headers include X-WP-TotalPages.

python
import math

# Get first page to find total pages
response = wcapi.get("orders", params={"per_page": 100, "page": 1})
orders = response.json()
total_pages = int(response.headers.get('X-WP-TotalPages', 1))

all_orders = orders
for page in range(2, total_pages + 1):
    more_orders = wcapi.get("orders", params={"per_page": 100, "page": page}).json()
    all_orders.extend(more_orders)

Now process all_orders as above.

Step 5: Filter by Order Status or Date Range

To export only completed orders, pass a status parameter:

python
params = {"status": "completed", "per_page": 100, "page": 1}

For a date range (e.g., last 30 days), use after and before:

python
from datetime import datetime, timedelta

thirty_days_ago = (datetime.now() - timedelta(days=30)).isoformat()
params = {"after": thirty_days_ago, "per_page": 100, "page": 1}

Combine both if needed. The API uses ISO 8601 format.

Pro Tips / Common Mistakes

  • JSONDecodeError: If the API returns an HTML page (e.g., a 404 or maintenance page), the JSON parser fails. Always check response.status_code first.
  • Rate limiting: WooCommerce REST API has no hard limit, but aggressive requests can slow your store. Add time.sleep(0.5) between pages if you hit issues.
  • Memory: For stores with 10,000+ orders, consider writing rows incrementally instead of building a huge list in memory.
  • Skip empty SKUs: Some products (e.g., variations) may have no SKU. Use item.get('sku', '') to avoid KeyError.

FAQ

Can I export orders from a specific date range?

Yes. Use the after and before parameters with ISO 8601 timestamps (e.g., after=2024-01-01T00:00:00).

Why does my CSV show garbled characters in Excel?

Excel expects a UTF-8 BOM. Use encoding='utf-8-sig' when opening the file.

How do I handle pagination for stores with many orders?

Check the X-WP-TotalPages header and loop through all pages, concatenating the results.

Can I export only certain order statuses?

Yes. Pass a status parameter (e.g., status=completed) in the request.

What if I get a 401 or 403 error?

Your API credentials may be invalid or have wrong permissions. Regenerate them with at least Read access.

Conclusion

With this Python script, you can export WooCommerce orders and line items to a clean CSV — each product on its own row with the order number, customer, SKU, quantity, and total. The script handles pagination, status and date filters, and saves an Excel-friendly UTF-8 CSV.

Copy the code, update your store URL and API keys, and run it. You’ll have a fully flattened dataset ready for analysis or accounting.

Related posts:

Why use WordPress for your Website?

Card Testing Bots Skip Your Checkout Form. Stop Them

WordPress Patched Itself. Your Store May Still Be Owned

Tags: APICSVdata exportPythonREST APIWooCommerce
SummarizeShare2
Paul H

Paul H

An SEO and Content expert having experience working with Enterprise-level corporations as an SEO and Digital Marketing Specialist. Contact me for any type of SEO/SEM, Digital Marketing service- paul@e-commpartners.com

Related Stories

Illustration of a website window with a cracked shield and a hidden second door behind it, representing a WordPress site still compromised after patching

WordPress Patched Itself. Your Store May Still Be Owned

by Paul H
August 2, 2026
0

WordPress force-updated millions of sites against the wp2shell RCE chain. That fixed the hole. It did not remove anyone who was already inside. Here are the checks that...

Illustration of a stopwatch merged with a shopping cart racing forward, showing how site speed drives online sales

A 0.1s Speed Boost Lifted Retail Sales 8.4%. Here’s How

by Paul H
July 22, 2026
0

Deloitte measured what one tenth of a second is worth to an online store: 8.4% more conversions. Here are the three metrics to fix first.

Editorial illustration comparing WooCommerce hosting options

WooCommerce Hosting Comparison for Growing Stores

by Paul H
July 22, 2026
0

Growing WooCommerce stores should compare hosts by performance, backups, staging, support, security, traffic limits and renewal pricing.

Editorial illustration comparing Shopify and WooCommerce total cost

Shopify vs WooCommerce: Total Cost Comparison

by Paul H
July 22, 2026
0

Shopify is simpler to budget. WooCommerce is flexible but shifts costs into hosting, plugins, maintenance and developer time.

Recommended

Technical SEO audit workflow showing disconnected pages being reconnected through internal linking structure

Orphan Pages SEO: Technical Audit Guide to Fix Site Structur

May 17, 2026
Implementing AI Predictive Analytics in Your E-commerce Strategy

Beyond Recommendations: AI Predicts What Customers Want Before They Know

May 26, 2025

Popular Story

  • AI is revolutionizing retail

    The AI Revolution in Retail: Where We Stand Today

    21 shares
    Share 8 Tweet 5
  • Autonomous Deliveries: The Future of eCommerce Logistics and the Rise of Drones and Self-Driving Vehicles

    18 shares
    Share 7 Tweet 5
  • Why use WordPress for your Website?

    17 shares
    Share 7 Tweet 4
  • Apple Mac Studio M4 Max Review: Creator Powerhouse

    17 shares
    Share 7 Tweet 4
  • Top 10 Advanced SEO Techniques & Strategies for 2024

    15 shares
    Share 6 Tweet 4

E-commerce Partners covers the latest in online retail, AI, and digital shopping trends. We publish news, guides, and analysis to help store owners and marketers stay ahead.

Follow us

Recent Posts

Shipping parcels moving toward an EU-style gateway, illustrating the August 2026 PPWR packaging deadline

EU Packaging Rules Hit Aug 12. No Grace Period.

August 3, 2026
Abstract illustration of a single consumer deletion request fanning out to many company data servers on a repeating 45-day cycle

California Delete Act: The $200-a-Day Clock Started

August 3, 2026

Weekly Newsletter

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
No Result
View All Result
  • Landing Page
  • Buy JNews
  • Support Forum
  • Pre-sale Question
  • Contact Us

© 2026 E-commerce Partners - E-commerce & AI news .