Pergunta

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.

Foi útil?

Solução

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
    );
   ......
}

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top