How to form a CSV file to download with Magento 2

In Magento 2 project, you will require to form a CSV File to Download with Magento 2 very often. So today, I’ll show you how to form a CSV File to Download with Magento 2 .  Let’s see!

Please form your controller file, in this example is Download.php in app/code/[Name_Space]/[Your_Module]/Controller/Download

For instance, I have to download CSV file that contain all id, SKU, name of products in the system.

<?php

/**

 *

 * Copyright © 2016 Magento. All rights reserved.

 * See COPYING.txt for license details.

 */

namespace [Your_NameSpace]\[Your_Module]\Controller\Download;



use Magento\Framework\App\Action\Context;

use Magento\Framework\View\Result\PageFactory;



class Download extends \Magento\Framework\App\Action\Action

{

/**

* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory

*/

protected $_productCollectionFactory;

    

public function __construct(

     Context $context,

     \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory

) {

     $this->_productCollectionFactory = $productCollectionFactory;

     parent::__construct($context);

}

public function execute()

{

     $notificationId = $this->getRequest()->getParam('notification_id');

     $heading = [

         __('Id'),

         __('SKU'),

         __('Name')

     ];

     $outputFile = "ListProducts". date('Ymd_His').".csv";

     $handle = fopen($outputFile, 'w');

     fputcsv($handle, $heading);

     foreach ($productCollection as $product) {

         $row = [

             $product->getId(),

             $product->getSku(),

             $product->getName()           

         ];

         fputcsv($handle, $row);

     }

     $this->downloadCsv($outputFile);

}



public function downloadCsv($file)

{

     if (file_exists($file)) {

         //set appropriate headers

         header('Content-Description: File Transfer');

         header('Content-Type: application/csv');

         header('Content-Disposition: attachment; filename='.basename($file));

         header('Expires: 0');

         header('Cache-Control: must-revalidate');

         header('Pragma: public');

         header('Content-Length: ' . filesize($file));

         ob_clean();flush();

         readfile($file);

     }

}

}

These are the technique to form a CSV File to Download with Magento 2. Hope all you guys can study magento 2 easier with our tutorial.

Last Update: April 7, 2018  

March 13, 2018   814   Nandini Ramachandran    Operations    
Total 2 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn