Thursday, September 27, 2012

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;
}

5 comments:

  1. Hi Bhoopendra, I wanted something like that but not in Admin back-end. Actually, m looking for adding a "Export to-CSV" Button in the front-end page like Products Details/view or order history so that the registered customer can also export the procuct details from front-end to CSV files. I would really appreciate if you can help me start this. Thank you.

    ReplyDelete
    Replies
    1. use following code in any custom module controller and pass product id by using in product view page

      $mage_csv = new Varien_File_Csv();
      $products_ids = array(id1,id2,id3);
      $products_model = Mage::getModel('catalog/product');
      $products_row = array();
      foreach ($products_ids as $pid)
      {
      $prod = $products_model->load($pid);
      $data = array();
      $data['sku'] = $prod->getSku();
      $data['name'] = $prod->getName();
      $data['price'] = $prod->getPrice();
      $products_row[] = $data;
      }
      $mage_csv->saveData($file_path, $products_row);

      Delete
  2. It worked perferct! Thanks!

    ReplyDelete