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)
CodeAs follows:
1 <? PHP
2
3 Class Table_export Extends Ci_controller {
4
5 Function _ Construct ()
6 {
7 Parent: :__ construct ();
8
9 // Here you should add some sort of user validation
10 // To prevent strangers from pulling your table data
11 }
12
13 Function Index ( $ Table_name )
14 {
15 $ Query = $ This -> DB-> get ( $ Table_name );
16
17 If (! $ Query )
18 Return False ;
19
20 // Starting the phpexcel Library
21 $ This -> Load-> Library ('phpexcel ');
22 $ This -> Load-> Library ('phpexcel/iofactory ');
23
24 $ Objphpexcel = New Phpexcel ();
25 $ Objphpexcel -> Getproperties ()-> settitle ("Export")-> setdescription ("NONE ");
26
27 $ Objphpexcel -> Setactivesheetindex (0 );
28
29 // Field Names in the first row
30 $ Fields = $ Query -> List_fields ();
31 $ Col = 0;
32 Foreach ( $ Fields As $ Field )
33 {
34 $ Objphpexcel -> Getactivesheet ()-> setcellvaluebycolumnandrow ( $ Col , 1, $ Field );
35 $ Col ++;
36 }
37
38 // Fetching the table data
39 $ Row = 2;
40 Foreach ( $ Query -> Result () As $ Data )
41 {
42 $ Col = 0;
43 Foreach ( $ Fields As $ Field )
44 {
45 $ Objphpexcel -> Getactivesheet ()-> setcellvaluebycolumnandrow ( $ Col , $ Row , $ Data -> $ Field );
46 $ Col ++;
47 }
48
49 $ Row ++;
50 }
51
52 $ Objphpexcel -> Setactivesheetindex (0 );
53
54 $ Objwriter = Iofactory: createwriter ( $ Objphpexcel , 'Excel5 ');
55
56 // Sending headers to force the user to download the file
57 Header ('Content-type: Application/vnd. MS-Excel ');
58 Header ('Content-Disposition: attachment; filename = "products _'. Date ('Dmy').'.xls "');
59 Header ('Cache-control: Max-age = 0 ');
60
61 $ Objwriter -> Save ('php: // output ');
62 }
63
64 }
4. Test
Join the database with the table name products, you can access the http://www.yoursite.com/table_export/index/products to export the Excel file.
Reference: http://www.dannyherran.com/2011/03/exporting-your-mysql-table-data-with-phpexcel-codeigniter/