Monday, June 3, 2013

Export excel sheet in joomla 3.0

public function export() {
        $db = JFactory::getDBO();
        $query = 'SELECT * FROM #__table'
        $db->setQuery($query);
        $items = $db->loadObjectList();

        header('Content-type: application/text');
        header('Content-Disposition: attachment; filename="export.csv"');
        echo HPCSV::create($items);
    }

<?php
/**
 * Class to export/import data to CSV
 *
 * @author Hannes Papenberg
 * @license GNU/GPL
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

class HPCSV
{
    function create($data)
    {
        $csv = self::create_csv_file_header($
data);
        foreach ($data as $key=>$val){
            $csv .= self::create_csv_file_row($val);
        }
        return $csv;
    }
   
    function read($string)
    {
        $rows = explode("\n", $string);
        foreach($rows as &$row)
        {
            $row = explode(',',$row);
        }
        return $rows;
    }
   
    function create_csv_file_header($data)
    {
        $row = "";
        if (count($data)>0){
            foreach ($data[0] as $key=>$val)
            {
                if ($row){
                    $row .= ',' . $key;
                }else{
                    $row .= $key;
                }
            }
            $row .= "\n";
        }
        return $row;
    }
   
   
    function create_csv_file_row($row)
    {
        $res = "";
        foreach ($row as $key=>$val)
        {
            if ($res){
                $res .= ',' .'"'. $val.'"';
            }else{
                $res .= '"'.$val.'"';
            }
        }
        $res .= "\n";
   
        return $res;
    }
   
}

No comments:

Post a Comment

Thank you for your Comment....

Popular Posts