In this guide, we’ll walk you through a simple 3-step process of Magento 2 Export Orders CSV programmatically.
Yes! You can programmatically export orders in .csv format from your Magento 2 using the Magento 2 API and in just a few easy-to-follow steps.
Let’s get started!
Why Export Orders Programmatically?
Before we jump into the steps, here’s a quick look at why you might want to export orders using code:
- Automate order reporting or backups.
- Feed order data into third-party tools.
- Customize exports beyond what built-in features offer.
Now, onto the how.
Here are the steps to programmatically export orders to CSV in Magento 2.
3 Steps to Export Orders to CSV Programmatically in Magento 2
Step 1: Set Up a Custom Module
First, we’ll create a basic module that Magento can recognize.
Create module.xml
Path: app/code/Custom/Module/etc/module.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Custom_Module" setup_version="1.0.0">
</module>
</config>
|
Create registration.php
Path: app/code/Custom/Module/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Custom_Module',
__DIR__
);
|
With that, your module is now registered. Don’t forget to run:
php bin/magento setup:upgrade
Step 2: Set Up Routes for the Module
Next, let’s define a custom route so you can trigger the export from your browser.
Create routes.xml
Path: app/code/Custom/Module/etc/frontend/routes.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<router id="standard">
<route frontName="custom" id="custom">
<module name="Custom_Module"/>
<route>
<router>
</config>
|
Now, when you access yourstore.com/custom/index/exportorders, Magento knows what to do.
Step 3: Create a Controller to Generate the CSV File with Export Order Data
We’ll fetch order data and write it into a CSV (Comma-separated values) file.
Create ExportOrders.php
Path: app/code/Custom/Module/Controller/Index/ExportOrders.php
<?php
namespace Custom\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
class ExportOrders extends Action
{
protected $fileFactory;
protected $orderRepository;
protected $searchCriteriaBuilder;
protected $_filesystem;
public function __construct(
Context $context,
FileFactory $fileFactory,
OrderRepositoryInterface $orderRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\Filesystem $filesystem
) {
$this->fileFactory = $fileFactory;
$this->orderRepository = $orderRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_filesystem = $filesystem;
parent::__construct($context);
}
public function execute()
{
$searchCriteria = $this->searchCriteriaBuilder->create();
$orders = $this->orderRepository->getList($searchCriteria)->getItems();
$csvData = [];
$csvData[] = ['Order ID','Customer Email','Order Total'];
foreach ($orders as $order) {
$csvData[] = [
$order->getEntityId(),
$order->getCustomerEmail(),
$order->getGrandTotal()
];
}
$fileName = 'orders.csv';
$filePath = 'export/' . $fileName;
$directory = $this->_filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$stream = $directory->openFile($filePath, 'w+');
foreach ($csvData as $rowData) {
$stream->writeCsv($rowData);
}
$stream->close();
$content = [
'type' => 'filename',
'value' => $filePath,
'rm' => true
];
$response = $this->fileFactory->create($fileName, $content, DirectoryList::VAR_DIR);
return $response;
}
}
|
How to Export Additional Order Data in Magento 2 CSV Programmatically
Let’s say you also want to include the order status in the export. Easy fix!
Just tweak this part:
$csvData = [];
$csvData[] = ['Order ID', 'Customer Email', 'Order Total', 'Order Status'];
foreach ($orders as $order) {
$csvData[] = [
$order->getEntityId(),
$order->getCustomerEmail(),
$order->getGrandTotal(),
$order->getStatus()
];
}
|
You can customize the CSV columns however you like; billing info, shipping address, payment method, and more.
How to Access the Exported Orders CSV in Magento 2
Once everything is set, simply visit: {your-base-url}/custom/index/exportorders
Your CSV file will automatically download with all the order data.
Need an Easier Way?
If you'd rather not build from scratch or want a more robust solution with filtering, scheduling, and additional export fields, you can check out our module. It’s built for store owners who want more control without coding.
Check out Magento 2 Export Orders extension
Wrapping Up!
We hope this guide gave you a clear and actionable way to export orders programmatically in Magento 2 to a .csv file.
If you're stuck or need help customizing the export, our Magento experts are just a message away.