Hello Everyone,
In this blog, we will learn about how to Automatically Generate a CSV file on Order Place in Magento 2.
When Order is Placed Store Owners went to order information to fulfill the order process.
Generating a CSV when an order is placed is helped to get order information easily.
Without wasting your time, let us guide you straight away. Follow the easy step given below to Automatically generate CSV on Order Place in Magento 2.
STEPS FOR AUTOMATICALLY GENERATE CSV FILE IN ORDER PLACE IN MAGENTO 2
Step 1: Create events.xml file
app/code/Vendor/Extension/etc/events.xml
<?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_generate_csv'
instance='Vendor\Extension\Observer\GenerateCSV'
/>
</event>
</config>
Step 2: Create GenerateCSV.php file
app/code/Vendor/Extension/Observer/GenerateCSV.php
<?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();
$customer firstname = $order->getCustomerFirstname();
$customer lastname = $order->getCustomerLastname();
$customeremail = $order->getCustomerEmail();
$filepath = 'export csv order/'.$order_id.'.csv';
$this->directory->create('export csv order');
$stream = $this->directory->openFile($filepath, 'w+');
$stream->lock();
$header = ['Order Id', 'Customer FirstName', 'Customer LastName', 'Customer Email'];
$stream->writeCsv($header);
$data[] = $order_id;
$data[] = $customer firstname;
$data[] = $customer lastname;
$data[] = $customer email;
$stream->writeCsv($data);
}
}
Step 3: Finally run the below commands
$ php bin/magento cache:clean
$ php bin/magento cache:flush
Step 4: Output:
Final Thoughts:
So this was the easiest way which we have told you in this blog. This is how you can generate a CSV file on every order placed in Magento 2. Hope you liked the blog.
So quickly go to the comment box and tell me how you like this blog?
Stay tuned with us on our site to get new updates of Magento.
Thanks for reading and visiting our site.
