Phpexcel is a PHP class library for manipulating Officeexcel documents based on Microsoft's OPENXML Standard and PHP language. You can use it to read and write spreadsheets in different formats. And CodeIgniter is a powerful PHP framework. The combination of the two can play a very good effect!
1. Preparatory work
Download phpexcel:http://phpexcel.codeplex.com
This is a powerful Excel library that only demonstrates the ability to export Excel files, most of which may be unnecessary.
2. Install Phpexcel to CodeIgniter
1 Extract the contents of the Classes folder in the compressed package into the Application\libraries\ directory, the directory structure is as follows:
--application\libraries\phpexcel.php
--application\libraries\phpexcel (folder)
2) Modify application\libraries\phpexcel\iofactory.php file
--Change its class name from Phpexcel_iofactory to Iofactory and follow the CI class naming rules.
--change its constructor to public
3. Install finished, write a controller to export Excel (Controller)
The code is as follows:
Copy Code code 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 join a database with the table named products, you can access the Http://www.yoursite.com/table_export/index/products export Excel file.