Thursday 14 February 2013

How to create csv file using magento

Creating csv files in magento is very easy and flexiable

         $fileName = "example.csv";
         $file_path = Mage::getBaseDir('media').DS.$fileName; // path of the file

         $mage_csv = new Varien_Convert_Parser_Csv();

          try {
         $mage_csv->saveData($file_path, $rows); //note $rows will be two dimensional array
         $mage_csv->setData($rows);
         $result = $mage_csv->unparse();
      
              } catch (Exception $e) {
         echo $e->getMessage();exit;
         }

         header("Content-type: application/csv");
         header("Content-Disposition: attachment; filename=$fileName");
         header("Pragma: no-cache");
         header("Expires: 0");
         echo $result->getData();
         exit;

Example
      
     $fileName = "example.csv";
         $file_path = Mage::getBaseDir('media').DS.$fileName; // path of the file

         $mage_csv = new Varien_Convert_Parser_Csv();
         $rows = array();
        $_data['n'] = 'name';
         $_data['a'] = 'address';
         $_data['g'] = 'gender';
         $rows[]=$_data;

           $data['n'] = 'Ram';
         $data['a'] = 'Hyd';
         $data['g'] = 'Male';
        $rows []=$data;
          try {
         $mage_csv->saveData($file_path, $rows); //note $rows will be two dimensional array
         $mage_csv->setData($rows);
         $result = $mage_csv->unparse();
      
              } catch (Exception $e) {
         echo $e->getMessage();exit;
         }

         header("Content-type: application/csv");
         header("Content-Disposition: attachment; filename=$fileName");
         header("Pragma: no-cache");
         header("Expires: 0");
         echo $result->getData();
         exit;

3 Comments:

At 14 February 2013 at 21:07 , Blogger Unknown said...

Stop Excel from automatically converting certain text values to dates/numbers just folow below

putting an '=' before the double quotes will accomplish what you want. It forces the data to be text.

eg. ="2008-10-03",="more text"

 
At 15 April 2013 at 23:55 , Blogger Unknown said...

'="'.Mage::helper('customerattributeset')->changeDateformat($date_intrv[count($date_intrv)-1],'d/m/Y').'"';

 
At 14 June 2018 at 03:51 , Blogger Reader said...

thank you buddy.
you saved my time and life.

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home