How to Automatically Generate CSV File 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

Comments