Magento : Export the CSV file From Grid

Export the data from grid is very common functionality for any website. These functionality applied normally on report section of projects, here i am telling you how to export excel/CVS/XML file from magento admin grid. Magento provides getCsvFile() method to export data from grid.
We need to follow following steps to achieve our goal.

You can also check other tutorial of Magneto export,

Step 1: We will Export CSV/Excel/XML button on admin grid.

protected function _prepareColumns()  
  {  
        // add columns in the Grid  
        $this->addColumn('bar_code', array(  
              'header'    => Mage::helper('testmodule')->__(Name),  
              'align'     =>'right',  
              'width'     => '20px',  
              'index'     => 'bar_code',  
        ));  
 
              
           $this->addExportType('*/*/exportCsv', Mage::helper('ticketpurchase')->__('CSV'));  
            $this->addExportType('*/*/exportXml', Mage::helper('ticketpurchase')->__('XML'));  
            $this->addExportType('*/*/exportExcel', Mage::helper('ticketpurchase')->__('EXCEL'));  
      
        return parent::_prepareColumns();  
    }  

Step 2: Now we will write logic in method to export file based on selected format.

/** 
    * @function         : exportCsvAction 
    * @created by       : parvez Alam 
    * @description      : Export data grid to CSV format 
    * @params           : null 
    * @returns          : array 
    */  
    public function exportCsvAction()  
    {  
        $fileName   = 'purchasedTicket.csv';  
        $content    = $this->getLayout()->createBlock('test_ticketpurchase_block_adminhtml_ticketpurchase_grid');  
          
        $this->_prepareDownloadResponse($fileName, $content->getCsvFile());  
    }