如何使用codeigniter将表数据导出到.csv文件?

时间:2016-03-05 11:12:47

标签: mysql excel codeigniter export phpexcel

我正在使用codeigniter,我已经列出了表中的记录。我想将所有记录下载到excel。我使用过PHPExcel库,但它不支持。你能帮忙解决一下这个问题吗?

2 个答案:

答案 0 :(得分:1)

我使用PHPExcel完成了它。查看此链接以将PHPExcel加载到库文件http://blog.mohamadikhwan.com/2013/01/integrating-phpexcel-into-codeigniter/

以下代码是在excel中下载值

    $this->load->library('excel');
    //Create a new Object
    $objPHPExcel = new PHPExcel();
    // Set the active Excel worksheet to sheet 0
    $objPHPExcel->setActiveSheetIndex(0); 



    $heading=array('Name','DOB'); //set title in excel sheet
    $rowNumberH = 1; //set in which row title is to be printed
    $colH = 'A'; //set in which column title is to be printed
    foreach($heading as $h){ 
        $objPHPExcel->getActiveSheet()->setCellValue($colH.$rowNumberH,$h);
        $colH++;    
    }


    $export_excel = $this->db->query("YOUR QUERY")->result_array();
    $rowCount = 2; // set the starting row from which the data should be printed
    foreach($export_excel as $excel)
    {         
        $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $excel['field name']); 
        $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $excel['field name']); 
        $rowCount++; 
    } 

    // Instantiate a Writer 
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');

    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="part_stock."".xls"');
    header('Cache-Control: max-age=0');

    $objWriter->save('php://output');
    exit();

答案 1 :(得分:1)

如果你想要的只是CSV数据,你就不需要图书馆了。 Codeigniter支持开箱即用:

$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$q         =  $this->db->get($yourTableName);
$delimiter = ",";
$nuline    = "\r\n";

force_download($yourTableName.'.csv', 
               $this->dbutil->csv_from_result($q, $delimiter, $nuline));