Magento

How to Download Csv File in Magento 2

Written by Jigar Patel

Sep 26

How to Download Csv File in Magento 2

we will explain you, How to Download Csv File in magento 2. CSV (Comma Separated Value) file is one of the most easy way to import/export magento entity data.download CSV File Programmatically in Magento 2 by FileFactory Class.

How to Download Csv File in Magento 2

\Magento\Framework\App\Response\Http\FileFactory used to create CSV and download CSV by Magento way. create() function in FileFactory.php is used for create CSV file.

<?php
namespace Dolphin\Csv\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;

class GetCsv extends Action
{
    public function __construct(
        Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory
    ) {
        $this->fileFactory = $fileFactory;
        parent::__construct($context);
    }
 
    public function execute()
    {
        $filepath = 'export/allcustomer.csv';
        $downloadedFileName = 'allcustomer.csv';
        $content['type'] = 'filename';
        $content['value'] = $filepath;
        $content['rm'] = 1;
        return $this->fileFactory->create($downloadedFileName, $content, DirectoryList::VAR_DIR);
    }
}

Here, $filepath is the path of the file under var/ folder. $downloadedFileName is the file name when it get downloaded on client side. If $content[‘rm’] is equal to 1 then the file will be deleted from server after it has been downloaded.

If you want to know how can you create csv file programmatically then please check out our blog How to create a CSV file in magento 2”.

I Hope, This instruction will be helpful for you.

If you have any difficulties regarding this blog, do consider them posting in the Comments section below!

I’m here to help.

Thank you!

Written by Jigar Patel

Our Magento Store

Do not miss a chance to grab exciting offers on Magento Development at Dolphin Web Solution. We are providing discounts on various Magento services this season. Go and grab yours today at our Magento Store.

Multiple Wishlist for Magento 2

Multiple Wishlist for Magento 2

₹ 3106

Wallet and Reward Points for Magento 2

Wallet and Reward Points for Magento 2

₹ 9476

RMA for Magento 2

RMA for Magento 2

₹ 11865

₹ 14254
Abandoned Cart Email for Magento 2

Abandoned Cart Email for Magento 2

₹ 6291

Simple Details on Configurable Product for Magento 2

Simple Details on Configurable Product for Magento 2

₹ 7883

₹ 9476
Frequently Bought Together for Magento 2

Frequently Bought Together for Magento 2

₹ 5494

₹ 7087

Let's Start Your Project

Get free consultation for your digital product idea to turn it into reality!

Copyright © 2023 DOLPHIN WEB SOLUTION. All rights reserved.

TO TOP