How To

Magento 2: Download Export File Directly Without Cron Schedule

Hello Magento Friends,

Today’s discussion is about How to Download Export File Directly Without a Cron Schedule in Magento 2.

Using Magento export functionality users can download CSV files of data. Export data into CSV file Programmatically in Magento 2

At that time cron is scheduled to carry out the export operation. But if the user wants to download the CSV file without cron scheduling, you can use the following code.

Steps to Download Export File Directly Without Cron Schedule in Magento 2:

Step 1: First, we need to create a “di.xml” file inside our extension at the following path

app\code\Vendor\Extension\etc\adminhtml\

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:ObjectManager/etc/config.xsd">
    <preference for="Magento\ImportExport\Controller\Adminhtml\Export\Export" type="Vendor\Extension\Controller\Adminhtml\Export\Export" />
</config>

Step 2: After that, we need to create an “ Export.php” file inside the extension Controller directory

app\code\Vendor\Extension\Controller\Adminhtml\Export\

And add the below code snippet

<?php

declare(strict_types=1);

namespace Vendor\Extension\Controller\Adminhtml\Export;

use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\MessageQueue\PublisherInterface;
use Magento\ImportExport\Controller\Adminhtml\Export as ExportController;
use Magento\ImportExport\Model\Export as ExportModel;
use Magento\ImportExport\Model\Export\Entity\ExportInfoFactory;

/**
* Controller for export operation.
*/
class Export extends ExportController implements HttpPostActionInterface
{
    /**
    * @var \Magento\Framework\App\Response\Http\FileFactory
    */
    protected $fileFactory;

    /**
    * @var \Magento\Framework\Session\SessionManagerInterface
    */
    private $sessionManager;

    /**
    * @var PublisherInterface
    */    
    private $messagePublisher;

    /**
    * @var ExportInfoFactory
    */
    private $exportInfoFactory;

    /**
    * @param Context $context
    * @param FileFactory $fileFactory
    * @param \Magento\Framework\Session\SessionManagerInterface|null $sessionManager
    * @param PublisherInterface|null $publisher
    * @param ExportInfoFactory|null $exportInfoFactory
    */
    public function __construct(
           Context $context,
           FileFactory $fileFactory,
           \Magento\Framework\Session\SessionManagerInterface $sessionManager = null,
           PublisherInterface $publisher = null,
           ExportInfoFactory $exportInfoFactory = null,
           ExportModel $exportModel)
    {
        $this->fileFactory = $fileFactory;
        $this->sessionManager = $sessionManager ?: \Magento\Framework\App\ ObjectManager::getInstance()
        ->get(\Magento\Framework\Session\SessionManagerInterface::class);
        $this->messagePublisher = $publisher ?: \Magento\Framework\App\ ObjectManager::getInstance()
        ->get(PublisherInterface::class);
        $this->exportInfoFactory = $exportInfoFactory ?:
        \Magento\Framework\App\ObjectManager::getInstance()->get(
        ExportInfoFactory::class);
        $this->exportModel = $exportModel;
        parent::__construct($context);
    }

    /**
    * Load data with filter applying and create file for download.
    *
    * @return \Magento\Backend\Model\View\Result\Redirect
    */
    public function execute()
    {
        if ($this->getRequest()->getPost(ExportModel::FILTER_ELEMENT_GROUP)) 
        {
            try
            {
                $params = $this->getRequest()->getParams();
                //$model = $this->_objectManager->create(\Magento\ImportExport\Model\ Export::class);
                $this->exportModel->setData($this->getRequest()->getParams());
                $this->sessionManager->writeClose();

                return $this->fileFactory->create(
                $this->exportModel->getFileName(),
                $this->exportModel->export(),
                \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR,
                $this->exportModel->getContentType());

                /** @var ExportInfoFactory $dataObject */
                $dataObject = $this->exportInfoFactory->create(
                $params['file_format'],
                $params['entity'],
                $params['export_filter']);

                $this->messagePublisher->publish('import_export.export', $dataObject);
                $this->messageManager->addSuccessMessage(
                __('Message is added to queue, wait to get your file soon'));
            }
            catch (\Exception $e)
            {
                $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
                $this->messageManager->addError(__('Please correct the data sent value.'));
            }
        }
        else
        {
            $this->messageManager->addError(__('Please correct the data sent value.'));
        }

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ 
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $resultRedirect->setPath('adminhtml/*/index');
        return $resultRedirect;
    }
}

Conclusion:

By doing so, you can Download Export File Directly Without Cron Schedule in Magento 2. If you have any doubt regarding the above steps, contact me via the comment section. I will be right back to you. Share the article with your friends and stay in touch with us!

Happy Coding!

Click to rate this post!
[Total: 1 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.🏏

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 day ago

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…

3 days 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…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

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

4 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…

5 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.…

1 week ago