Import and Export Orders in Magento 2
Vinh Jacker | 2024-18-12 15:30
Efficient order management is vital for organizing transaction data and maintaining smooth e-commerce operations. In Magento 2, exporting and importing orders allows businesses to streamline data handling, enabling better analysis, decision-making, and overall performance optimization.
This guide explores the steps and best practices for exporting and importing orders in Magento 2. By mastering these techniques, you’ll unlock valuable insights into customer behavior, optimize operational efficiency, and elevate the shopping experience. Whether you’re gathering transaction data for analysis or importing orders for better management, this guide will empower you to take full control of your Magento 2 order processes.
Supported File Formats for Import and Export Orders
In Magento 2, store admins can import and export data using various formats. CSV and XML are the primary options. Each format has a distinct file structure.
CSV
CSV (Comma-Separated Values) files store data in plain text, with commas separating each value. They’re ideal for managing smaller data sets and are compatible with most software. You can open and edit CSV files using any basic text editor. The CSV format is simple and user-friendly, which makes the transfer of information about orders easy.
XML
XML (Extensible Markup Language) files can be accessed using text editors, web browsers, Excel, or an XML Viewer. They store detailed information, including images and graphs, through tags that define content blocks. This structure is useful for managing large or complex data sets.
3 Effective Methods to Export Orders in Magento 2
Exporting orders in Magento 2 is essential for maintaining transaction records, performing analysis, and streamlining order management. Here are three effective methods to export orders from your Magento 2 store:
Method 1: Export orders using the Magento 2 admin panel
#1. Login to the Magento 2 Admin Panel and navigate to the Sale
> Orders
#2. On the Orders
page, you’ll see a list of all store orders. Each row represents an individual order, with columns showing details, including:
- ID
- Purchase Point
- Purchase Date
- Bill-to Name
- Ship-to Name
- Grand Total (Base)
- Grand Total (Purchased)
- Status
- Action
- Allocated sources
- Braintree Transaction Source
#3. To select specific orders for export, click on the checkboxes next to the order IDs. If you want to export all orders, tick the checkbox in the header row to mark all visible orders.
#4. With the desired orders selected, click on the Export
located above the orders list to expand the menu options.
#5. Select the file format (CSV or XML).
#6. Press on the Export
button to begin the export process, and the resulting CSV file will contain your order data as seen in the default view.
Method 2: Export orders programmatically using custom data
To export orders programmatically using custom data in Magento 2, you need to follow these steps:
#1. Create file db_schema.xml
in your module
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="sales_order_grid" resource="sales" comment="Sales Flat Order Grid">
<column xsi:type="varchar" name="coupon_code" nullable="true" length="255"/>
<column xsi:type="longtext" name="items" nullable="true"/>
<column xsi:type="varchar" name="shipping_region" nullable="true" length="255"/>
<column xsi:type="varchar" name="shipping_postcode" nullable="true" length="255"/>
<column xsi:type="varchar" name="shipping_city" nullable="true" length="255"/>
<column xsi:type="varchar" name="shipping_street" nullable="true" length="255"/>
<column xsi:type="varchar" name="shipping_fax" nullable="true" length="255"/>
<column xsi:type="varchar" name="shipping_telephone" nullable="true" length="255"/>
<column xsi:type="varchar" name="shipping_company" nullable="true" length="255"/>
<column xsi:type="varchar" name="shipping_country" nullable="true" length="255"/>
<column xsi:type="varchar" name="shipping_vat" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_region" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_postcode" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_city" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_street" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_fax" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_telephone" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_company" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_country" nullable="true" length="255"/>
<column xsi:type="varchar" name="billing_vat" nullable="true" length="255"/>
</table>
</schema>
#2. Create file di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Ui\Model\Export\ConvertToCsv" type="Mageplaza\BetterOrderGrid\Model\Export\ConvertToCsv"/>
</config>
#3. Create the Plugin:
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_BetterOrderGrid
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\BetterOrderGrid\Model\Export;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Ui\Model\Export\ConvertToCsv as UiConvertToCsv;
use Magento\Ui\Model\Export\MetadataProvider;
use Mageplaza\BetterOrderGrid\Helper\Data;
/**
* Class ConvertToCsv
*
* @package Mageplaza\BetterOrderGrid\Model\Export
*/
class ConvertToCsv extends UiConvertToCsv
{
/**
* @var Data
*/
protected $helperData;
/**
* ConvertToCsv constructor.
*
* @param Filesystem $filesystem
* @param Filter $filter
* @param MetadataProvider $metadataProvider
* @param Data $helperData
* @param int $pageSize
*
* @throws FileSystemException
*/
public function __construct(
Filesystem $filesystem,
Filter $filter,
MetadataProvider $metadataProvider,
Data $helperData,
$pageSize = 200
) {
$this->helperData = $helperData;
parent::__construct($filesystem, $filter, $metadataProvider, $pageSize);
}
/**
* Returns CSV file
*
* @return array
* @throws FileSystemException
* @throws LocalizedException
*/
public function getCsvFile()
{
$component = $this->filter->getComponent();
$name = hash('md5', microtime());
$file = 'export/' . $component->getName() . $name . '.csv';
$this->filter->prepareComponent($component);
$this->filter->applySelectionOnTargetProvider();
$dataProvider = $component->getContext()->getDataProvider();
$fields = $this->metadataProvider->getFields($component);
$options = $this->metadataProvider->getOptions();
$this->directory->create('export');
$stream = $this->directory->openFile($file, 'w+');
$stream->lock();
$stream->writeCsv($this->metadataProvider->getHeaders($component));
$i = 1;
$searchCriteria = $dataProvider->getSearchCriteria()
->setCurrentPage($i)
->setPageSize($this->pageSize);
$totalCount = (int) $dataProvider->getSearchResult()->getTotalCount();
while ($totalCount > 0) {
$items = $dataProvider->getSearchResult()->getItems();
foreach ($items as $item) {
if ($component->getName() === 'sales_order_grid' && $this->helperData->isEnabled()) {
$productArr = $this->helperData->convertOrderData($item->getEntityId());
$export_data = implode(' | ', $productArr);
$item->setProducts($export_data);
unset($productArr);
}
$this->metadataProvider->convertDate($item, $component->getName());
$stream->writeCsv($this->metadataProvider->getRowData($item, $fields, $options));
}
$searchCriteria->setCurrentPage(++$i);
$totalCount -= $this->pageSize;
}
$stream->unlock();
$stream->close();
return [
'type' => 'filename',
'value' => $file,
'rm' => true // can delete file after use
];
}
}
#4. Insert data into custom order columns.
Customize the code to insert data into your custom order columns as needed.
#5. Run setup upgrade
php bin/magento setup:upgrade
Then, click on the Export
button again to generate the file.
Method 3: Export orders via Magento 2 Export Order extension
The default order export functionality in Magento 2 can be limiting for businesses with diverse and complex needs. To overcome these restrictions, the Magento 2 Export Orders extension from Mageplaza provides a robust solution. This extension offers more flexibility and options for exporting order data, making it easier to manage and analyze your orders.
Highlight features of Mageplaza Orders Export:
- Quickly export customer data, including order, product, shipping, customer, and invoice information
- Export orders with predefined templates
- Supports 8 types of order exports
- Preview export results quickly
- Filter orders before exporting
- Schedule and run export profiles automatically
- Automatically upload export files to a remote server via FTP/SFTP
Key considerations when importing orders
Entity_id and Increment_id Attributes
When importing orders in Magento 2, the system uses two key attributes: entity_id
and increment_id
.
-
Entity_id
: This entity_id is an internal order identifier within Magento 2’s database. Magento 2 assigns entity_id automatically based on existing IDs in the database. If an imported order shares an ID with an existing order, Magento 2 will assign a new ID. -
Increment_id
: Representing the actual order number, the increment_id is unique and can be found in the order grid and on invoices. Magento 2 cannot handle two orders with identical increment_ids.
Note: When you import orders into Magento 2, you won’t see these orders immediately in the admin panel’s order list. Instead, you must navigate through the order details screen URL to view the imported orders.
Product Assignment
SKUs link products to orders. Even if a product isn’t available in the store, the imported order will still reference the product. However, you won’t be able to reorder that product since the store doesn’t have it in stock.
Customer Assignment
Orders are connected to customers through their email addresses. If the store doesn’t have a customer with a matching email, the imported order will still show the customer’s details, but that customer will be categorized as a guest.
How to Import Orders in Magento 2
10 Steps to Import Orders in Magento 2
Here is the step-by-step guide to help you import orders successfully:
1. From the Admin panel, select System
and click Import
2. Choose the data type you want to import.
3. Configure Import Behavior with the following options:
- Add/Update: Insert new orders into the Magento 2 database or modify existing orders with new information from your CSV file.
- Replace: Replace outdated or incorrect information with the most current data.
- Delete: Identify orders by entity_id in the CSV file and remove matching entries.
4. Set the Validation Strategy
to determine how the system handles errors during the import process:
- Stop on Error: Halt the import when errors occur
- Skip Error Entries: Bypass errors and continue importing
5. Set the error threshold in Allowed Errors Count. The system will stop importing if the errors exceed this number.
6. Specify the character for Multiple Value separators. It’s set to a comma (,) by default, but ensure it matches your CSV data format.
7. Click Download Sample
next to the Entity Type
field to download a sample template.
8. After preparing your CSV file, click the Choose File
button to choose the file for import.
9. Press Check Data
to validate the file for any mistakes
- If there are errors, resolve them in your CSV file and recheck
- If the file is error-free, proceed to the next step
10. Click on the Import button to start the import process.
Troubleshooting Common Issues
During the import and export of orders, unexpected errors may occur. These errors can cause performance bottlenecks and operational delays. Below are some common issues and effective ways to tackle these challenges.
“Invalid Data Format” Error
This typically occurs when the uploaded file does not meet Magento’s required format.
Solution: Make sure the file is in the correct CSV/XML format and follows Magento’s data schema. Refer to sample files provided by Magento or extensions for guidance.
“Required Field Missing” Error
Some mandatory fields (e.g., Order ID, Customer Email) are absent or incomplete.
Solution: Check the data file for missing columns or blank fields. Fill in the necessary information before re-importing.
“SKU Not Found” Error
The product SKUs in the order file do not exist in the Magento catalog.
Solution: Verify that all SKUs in the file match the products in Magento. Import missing products before reattempting to import the order.
“Export File Not Generated” Error
The export process is complete, but no file is generated.
Solution: Check server logs for errors. Ensure the selected export entity contains data and that file permissions are correctly configured.
FAQs about Importing and Exporting Orders in Magento 2
What formats can I use to export orders in Magento 2?
You can export orders in CSV (Comma-Separated Values) or XML (eXtensible Markup Language) formats.
What are the benefits of using Magento 2 Order Export extensions?
The Magento 2 Export Orders extensions provide several benefits for eCommerce businesses:
- Detailed Order Data: Export comprehensive details, including customer information, order items, billing and shipping addresses, and payment methods
- Automation: Support for automated exports at scheduled times using cron jobs
- Customization: Filter orders by date range, order number, or status
- Data Backup: Create backups of your order data for future needs by regularly exporting orders
What should I do before importing orders?
Before importing, ensure your CSV file is in the correct format and click Check Data
to validate it for any errors or inconsistencies.
Can I export orders by date range or order status?
Yes, you can apply filters such as date range or order status to export specific orders.
Can I clear import and export history manually or automatically?
Yes, you can clear import and export history manually or set it to clear automatically after a specified time.
What should I do to fix common errors when importing orders?
Common order import issues include incorrect data formatting, missing data fields, and extension-related conflicts. To fix these issues, you need to check error logs, review field mappings, and handle conflicts.
Can I use Magento 2 to export orders to third-party applications?
By using the Magento 2 Order Export extension from Mageplza, you can export orders to third-party applications. This tool integrates with external systems, making data sharing and management easy.
Conclusion
To sum up, importing and exporting orders in Magento 2 is a useful feature that helps businesses seamlessly manage order data, enhance productivity, and ensure smooth transactions. By following this guide and taking advantage of Magento 2’s powerful tool, you can manage the store’s data management effectively and keep your business running seamlessly.