1

How can i download csv file in magento 2 using below code is from controller,

public function execute(){
    $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
    $heading = array('Name','Sku','Qty','Price','Manufacturer');    
    $outputFile = "products_". date('Ymd_His').".csv";
    $handle = fopen($outputFile, 'w');
    fputcsv($handle, $heading);

               $this->downloadCsv($outputFile);
                $resultRedirect->setPath('*/*');
                return $resultRedirect;
}
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);
        } 
    }

Csv file not downloaded using above code. Data are getting right for me. Thanks.

1

1 Answer 1

2

I have checked your code. You just need to remove below code:

$resultRedirect->setPath('*/*');
return $resultRedirect;

You have no need to redirect any page while downloading any CSV file.

I Hope this will help you.

1
  • Thanks its working fine after remove/comment redirect url Commented May 26, 2016 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.