Magento : Add export CSV/XML functionality in magento admin grid

Magento : Add export CSV/XML functionality in magento admin grid

Consider module Bd_Demo and model Test, then
Add following lines in _prepareColumns() method of admin grid file
$this->addExportType('*/*/exportCsv', Mage::helper('demo')->__('CSV'));                              
$this->addExportType('*/*/exportXml', Mage::helper('demo')->__('XML'));

And add following methods in admin controller
public function exportCsvAction()
{
        $fileName   = 'test.csv';
        $content    = $this->getLayout()->createBlock('demo/adminhtml_test_grid')
            ->getCsv();

        $this->_sendUploadResponse($fileName, $content);
}

public function exportXmlAction()
{
        $fileName   = 'test.xml';
        $content    = $this->getLayout()->createBlock('demo/adminhtml_test_grid')
            ->getXml();

        $this->_sendUploadResponse($fileName, $content);
}

protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
{
        $response = $this->getResponse();
        $response->setHeader('HTTP/1.1 200 OK','');
        $response->setHeader('Pragma', 'public', true);
        $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
        $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
        $response->setHeader('Last-Modified', date('r'));
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', strlen($content));
        $response->setHeader('Content-type', $contentType);
        $response->setBody($content);
        $response->sendResponse();
        die;
}

Share this

Related Posts

Previous
Next Post »

4 comments

comments
27 July 2016 at 06:05 delete

Good article Jaybhai. Really helpful for beginner of core developer

Reply
avatar
27 January 2017 at 21:14 delete

Thanks for the best blog.it was very useful for me.keep sharing such ideas in the future as well.this was actually what i was looking for,and i am glad to came here!
magento development company in bangalore 

Reply
avatar
23 February 2017 at 22:23 delete

Thanks for you comment sahana

Reply
avatar

Pageviews from the past week