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

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!

Previous Article

Magento 2: How To Change Maximum Number Of Items To Display In Order Summary

Next Article

The Best Custom Magento Development Services

Write a Comment
    1. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨