Magento2 Export Button (CSv) in custom grid

bala.skpm picture bala.skpm · Feb 26, 2016 · Viewed 12.4k times · Source

How to add CSV export button in Custom grid in magento2. I have created a grid and form. Need to add csv export function in magento2.

Answer

Khodu Vaishnav picture Khodu Vaishnav · Feb 17, 2017

create your controller

<?php
namespace Yourpackage\Yourmodule\Controller\Adminhtml\Sample;

class ExportCsv extends \Magento\Backend\App\Action
{
  protected $_fileFactory;
  protected $_response;
  protected $_view;
  protected $directory;
  protected $converter;
  protected $resultPageFactory ;
  protected $directory_list;
  public function __construct( \Magento\Backend\App\Action\Context  $context,
         \Magento\Framework\View\Result\PageFactory $resultPageFactory
        ) {
        $this->resultPageFactory  = $resultPageFactory;
        parent::__construct($context);
}
 public function execute()
 {
    $fileName = 'yourfilename.csv';
    $resultPage = $this->resultPageFactory ->create();
    $content = $resultPage->getLayout()->getBlock('yourblockname')->getCsv();;
    $this->_sendUploadResponse($fileName, $content);

 }

protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream') {

     $this->_response->setHttpResponseCode(200)
        ->setHeader('Pragma', 'public', true)
        ->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)
        ->setHeader('Content-type', $contentType, true)
        ->setHeader('Content-Length', strlen($content), true)
        ->setHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"', true)
        ->setHeader('Last-Modified', date('r'), true)
        ->setBody($content)
        ->sendResponse();
    die;

 }
}

create your layout xml yourmodule_yourcontroller_exportcsv

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="yourmodule_yourcontroller_grid"/>
</page>