I am using magento 2.1 version. I am working to built export csv functionality on frontend. I am using below code:
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory
) {
$this->resultRawFactory = $resultRawFactory;
$this->fileFactory = $fileFactory;
parent::__construct($context);
}
/**
* Order view page
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$layout = $this->_view->getLayout();
$block = $layout->createBlock('Vendor\Modulename\Block\Myblock');
//do your custom stuff here
$fileName = 'mytest.csv';
$this->fileFactory->create(
$fileName,
null, //content here. it can be null and set later
DirectoryList::VAR_DIR,
'application/octet-stream', //content type here
null
);
$resultRaw = $this->resultRawFactory->create();
$resultRaw->setContents($block->getCollection()); //set content for download file here
}
How can I set collection to content in export file?