2

I want to export table content in downloadable csv format. In magento 1.x it can be achieve by _prepareDownloadResponse() how can we achieve same in magento 2. Looks like this function is missing in magento 2. Is their any alternative for this.

Please note that I don't want to use header() I am already using this which is working but i want to implement it by magento way as this gives warning at the time of extension upload in Magento connect.

5

You should try with \Magento\Framework\App\Response\Http\FileFactory::create().

Take a look import export module you can see how it works:

vendor/magento/module-import-export/Controller/Adminhtml/Import/Download.php

/**
 * Download sample file action
 *
 * @return \Magento\Framework\Controller\Result\Raw
 */
public function execute()
{
    ......
    $this->fileFactory->create(
        $fileName,
        null,
        DirectoryList::VAR_DIR,
        'application/octet-stream',
        $fileSize
    );
   ......
}
  • Please explain a bit more on how to do it with \Magento\Framework\App\Response\Http\FileFactory::create() – 7ochem Feb 9 '17 at 15:20
  • 1
    @khoa Thanks for the answer, it works for me. – Ashish Madankar M2 Professiona Feb 10 '17 at 6:03
4

This is not a new answer this is just addition to Khoa TruongDinh answers which helps me lot to solve my issue.

when we use above syntax second parameter would be data which we want to put in a csv.

In my example I have added sample data in function.

$fileSize is optional parameter so i skip it.

public function execute()
{
    ......
    $heads = "Col1,Col2,Col3";
    $colValues = "valC11,valC21,valC31" . PHP_EOL . "valC12,valC22,valC32";
    $data =  $heads . PHP_EOL . $colValues;
    $this->fileFactory->create(
        'sample.csv',
        $data,
        DirectoryList::VAR_DIR,
        'application/octet-stream'
    );
   ......
}

Hope this helps some one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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