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

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

13 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

2 days ago

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

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

2 days ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

2 weeks ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago