0

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?

0

1 Answer 1

0

Please try this, replace $resultRaw->setContents($block->getCollection()); with below

foreach($block->getCollection() as $data){
    $tmp = implode(",",$data->getData());
    $resultRaw->setContents($tmp);
}

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.