PHPExcel is a PHP class library used to operate OfficeExcel documents. It is based on Microsoft's OpenXML standard and PHP language. You can use it to read and write workbooks of different formats. Codeigniter is a powerful PHP framework. The combination of the two can achieve great results!
1. Preparations
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:
Copy codeThe Code is as follows: <? Php
ClassTable_exportextendsCI_Controller {
Function _ construct ()
{
Parent: _ construct ();
// Hereyoushouldaddsomesortofuservalidation
// Topreventstrangersfrompullingyourtabledata
}
Functionindex ($ table_name)
{
$ Query = $ this-> db-> get ($ table_name );
If (! $ Query)
Returnfalse;
// StartingthePHPExcellibrary
$ This-> load-> library ('phpexcel ');
$ This-> load-> library ('phpexcel/IOFactory ');
$ ObjPHPExcel = newPHPExcel ();
$ ObjPHPExcel-> getProperties ()-> setTitle ("export")-> setDescription ("none ");
$ ObjPHPExcel-> setActiveSheetIndex (0 );
// Fieldnamesinthefirstrow
$ Fields = $ query-> list_fields ();
$ Col = 0;
Foreach ($ fieldsas $ field)
{
$ ObjPHPExcel-> getActiveSheet ()-> setCellValueByColumnAndRow ($ col, 1, $ field );
$ Col ++;
}
// Fetchingthetabledata
$ Row = 2;
Foreach ($ query-> result () as $ data)
{
$ Col = 0;
Foreach ($ fieldsas $ field)
{
$ ObjPHPExcel-> getActiveSheet ()-> setCellValueByColumnAndRow ($ col, $ row, $ data-> $ field );
$ Col ++;
}
$ Row ++;
}
$ ObjPHPExcel-> setActiveSheetIndex (0 );
$ ObjWriter = IOFactory: createWriter ($ objPHPExcel, 'excel5 ');
// Sendingheaderstoforcetheusertodownloadthefile
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 ');
}
}
4. Test
When you add a table named products to the database, you can access http://www.yoursite.com/table_export/index/productsto export the excelfile.