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.  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 a CSV file that contains all IDs, SKUs, names of products in the system.

Build your Amazon-like multi-vendor marketplace website @ $249/- now!!!
             Get your free live demo now: Click here

How to create a CSV file to download with Magento 2?

<?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. Hope all of you guys can study Magento 2 easier with our tutorial.

Want to start an eCommerce store? Click here to start an online store.

CSV file to download with Magento 2


Posted

in

, ,

by

Comments

Leave a Reply

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