How to Download Csv File in Magento 2

Written by Jigar Patel

Sep 26, 2022

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!

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP