Magento 2 How To Create And Download a CSV Programmatically?

In Magento 2, we can create and download a CSV file programmatically using core FileFactory Class.

Path for the above class is \Magento\Framework\App\Response\Http\FileFactory. This class is generally used to create a CSV file using create() function in FileFactory.php.

Once you create a CSV file then if you need to download the file, you can do that also with following code snippet.
To download file, you need to write first something into CSV and then download that CSV file as given below

<?php
namespace Magemeta\CsvFile\Controller\Adminhtml\Index;
 
use Magento\Framework\App\Filesystem\DirectoryList;
 
class Export extends \Magento\Backend\App\Action
{
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Filesystem $filesystem
    ) {
        $this->_fileFactory = $fileFactory;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        parent::__construct($context);
    }
 
    public function execute()
    {
        $name = date('m_d_Y_H_i_s');
        $filepath = 'export/custom' . $name . '.csv';
        $this->directory->create('export');
        /**** Open a file in write mode ****/
        $stream = $this->directory->openFile($filepath, 'w+');
        $stream->lock();
        $columns = $this->getColumnHeader();
        foreach ($columns as $column) {
            $header[] = $column;
        }
        /* Write Header */
        $stream->writeCsv($header);
 
        $products[] = array(1,'Test1','test1',10);
        $products[] = array(2,'Test2','test2',20);
 
        foreach ($products as $item) {
            $itemData = [];
            $itemData[] = $item[0];
            $itemData[] = $item[1];
            $itemData[] = $item[2];
            $itemData[] = $item[3];
            $stream->writeCsv($itemData);
        }
 
        $content = [];
        $content['type'] = 'filename'; // must keep filename
        $content['value'] = $filepath;
        $content['rm'] = '1'; //it removes csv from var folder
 
        $csvfilename = 'Product.csv';
        return $this->_fileFactory->create($csvfilename, $content, DirectoryList::VAR_DIR);
        
    }
 
    /* Header Columns */
    public function getColumnHeader() {
        return ['Id','ProductName','Sku','Price'];
    }
}

When we will run above controller action on browser, browser will popup the csv download/open option from which we can download CSV file.

Hope this will help you guys!

Leave a Reply