Use of PHPExcel in the CICodeigniter framework | export data to an Excel file
Use of PHPExcel in the CI Codeigniter framework | export data to an Excel file. For more information, see. Use of PHPExcel in the CI framework | export data to an Excel file 1. prepare to start ......
Download PHPExcel: http://phpexcel.codeplex.com This is a powerful Excel database. only the Excel file export function is demonstrated here. most of the functions may not be needed. 2. install PHPExcel to Codeigniter 1) decompress the contents in the Classes folder of the compressed package to the application \ libraries \ directory. the directory structure is as follows: -- Application \ libraries \ PHPExcel. php -- Application \ libraries \ PHPExcel (folder) 2) modify the application \ libraries \ PHPExcel \ IOFactory. php file -- Change the class name from PHPExcel_IOFactory to IOFactory and follow the CI class naming rules. -- Change the constructor to public. 3. after the installation is complete, write a Controller for exporting the excel file) The code is as follows: Class Table_export extends CI_Controller { Function _ construct () { Parent: :__ construct (); // Here you should add some sort of user validation // To prevent strangers from pulling your table data } Function index ($ table_name) { $ This-> load-> database (); $ Query = $ this-> db-> query ("select * from '$ table_name' WHERE del = 1 "); // $ Query = mb_convert_encoding ("gb2312", "UTF-8", $ query ); If (! $ Query) Return false; // Starting the PHPExcel library $ This-> load-> library ('phpexcel '); $ This-> load-> library ('phpexcel/IOFactory '); $ ObjPHPExcel = new PHPExcel (); $ ObjPHPExcel-> getProperties ()-> setTitle ("export")-> setDescription ("none "); $ ObjPHPExcel-> setActiveSheetIndex (0) -> SetCellValue ('A1', iconv ('gbk', 'utf-8', 'Chinese hello ')) -> SetCellValue ('B2', 'World! ') -> SetCellValue ('C1', 'Hello '); // Field names in the first row $ Fields = $ query-> list_fields (); $ Col = 0; Foreach ($ fields as $ field) { $ ObjPHPExcel-> getActiveSheet ()-> setCellValueByColumnAndRow ($ col, 1, $ field ); $ Col ++; } // Fetching the table data $ Row = 2; Foreach ($ query-> result () as $ data) { $ Col = 0; Foreach ($ fields as $ field) { $ ObjPHPExcel-> getActiveSheet ()-> setCellValueByColumnAndRow ($ col, $ row, $ data-> $ field ); $ Col ++; } $ Row ++; } $ ObjPHPExcel-> setActiveSheetIndex (0 ); $ ObjWriter = IOFactory: createWriter ($ objPHPExcel, 'excel5 '); // Send the title to force the user to download the object Header ('content-Type: application/vnd. ms-excel '); Header ('content-Disposition: attachment; filename = "products_'.date('dmy'{.'.xls "'); Header ('cache-Control: max-age = 0 '); $ ObjWriter-> save ('php: // output '); } } ?> The table named products is added to the database, and you can access the http://www.yoursite.com/table_export/index/products to export the Excel file. Source |
Codeigniter, PHPExcel