Magento 2 Create CSV file and Download Programmatically

0
572
Magento 2 Create CSV file and Download Programmatically

In this article, you going to see discuss Magento 2 Create CSV file and Download Programmatically in detail and step by step.

If you are looking for this topic then you are at right place.

Let’s start with the topic Magento 2 Create CSV file and Download Programmatically

It is very easy to create CSV file and then download with the help of controller in case of Magento 2.

Let’s have a look step by step in creation of CSV file and download.

With the help of FileFactory Class, you can achieve this creation of export and download CSV, Excel or Text file programmatically.

So Let’s start with this point.

The file path for this Class called FileFactory Class is given as below as.

\Magento\Framework\App\Response\Http\FileFactory.

It is possible to create a CSV file and download programmatically with the use of a function called create() function in file called FileFactory.php

With the help of Core PHP source code it is easy to create CSV file and download but it best way to use in Magento coding standard.

Add the below code snippet in controller section in Magento 2.

Use the below code snippet you can create CSV file and download easily.

<?php
namespace VendorName\CSV\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 file */
        $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,'Test 1','test 1',200);
        $products[] = array(2,'Test 2','test 2',399);

        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'; //remove csv from var folder

        $csvfilename = 'Product.csv';
        return $this->_fileFactory->create($csvfilename, $content, DirectoryList::VAR_DIR);
        
    }

    /* Header Columns */
    public function getColumnHeader() {
        $headers = ['Id','Product name','SKU','Price'];
        return $headers;
    }
}

In above two code snippet two class file is very important one file which is name as File system and another class file named FileFactory.

Both file play an important role in case of creation of CSV file and download programmatically.

When you run the controller action csv file created and downloaded.

Free Magento 2 Themes – Best TOP 10 to Boost your E-commerce Store

Conclusion:

Using above code you can achieve Magento 2 create and download CSV.

I hope you like this article and if you have any query, please comment below.