How To

How to Automatically Generate CSV File on Every Order in Magento 2?

Hello Magento Friends,

This tutorial will provide the solution on How to Automatically Generate CSV File on Every Order in Magento 2?

When an order is placed, the store admin needs the order information to fulfill the delivery and shipment process correctly. Generating a CSV file of every order placed helps to get the order information easily.

Here I will explain how to Automatically Generate CSV files on every order in Magento 2. 

Steps to Automatically Generate CSV File on Every Order in Magento 2:

Step 1: Go to the below File Path

app\code\Vendor\Extension\etc\events.xml

Then, add the code as follows

<?xml version='1.0'?>
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='urn:magento:framework/Event/etc/events.xsd'>
   <event name='sales_order_place_after'>
        <observer
                name='sales_order_place_after'
                instance='Vendor\Extension\Observer\GenerateCSV'
        />
    </event>
</config>

Step 2: Next move to the below File Path

app\code\Vendor\Extension\Observer\GenerateCSV.php

Then add the below code snippet

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Filesystem\DirectoryList;

class GenerateCSV implements ObserverInterface
{
     protected $_objectManager;
     private $logger;
     private $productFactory;

     public function __construct(
          \Magento\Framework\ObjectManagerInterface $objectManager,
          \Psr\Log\LoggerInterface $logger,
          \Magento\Catalog\Model\ProductFactory $productFactory,
          \Magento\Framework\Filesystem $filesystem)
     {
          $this->_objectManager = $objectManager;
          $this->logger = $logger;
          $this->productFactory = $productFactory;
           $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
     }

     public function execute(\Magento\Framework\Event\Observer $observer)
     {  
          $order = $observer->getEvent()->getOrder();
          $order_id = $order->getIncrementId();
          $customerfirstname = $order->getCustomerFirstname();
          $customerlastname = $order->getCustomerLastname();
    
          $filepath = 'export/'.$order_id.'.csv';
          $this->directory->create('export');
          $stream = $this->directory->openFile($filepath, 'w+');
          $stream->lock();

          $header = ['Order Id', 'Customer FirstName', 'Customer LastName'];
          $stream->writeCsv($header);
        
          $data[] = $order_id;
          $data[] = $customerfirstname;
          $data[] = $customerlastname;
          $stream->writeCsv($data);
     }
}

Step 3: After that run the below command

php bin/magento setup:di:compile
php bin/magento cache:flush

Output:

You can see a CSV is generated like below for every order placed in your Magento 2 store.

Conclusion:

This way you can Automatically Generate CSV File on Every Order in Magento 2. Generate order report in Magento 2 to manage the shipment and delivery easily.

If you have doubts about the above steps, freely ask me through the comment section. Share the article with your friends and keep in touch with us!

Happy Coding!

Click to rate this post!
[Total: 2 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

    • Confirm you implement the code properly, and also debug the mode of your development, it must be into developer mode so it will show you proper error.

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 day ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 day ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

2 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

5 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

5 days ago