Example of generating and reading excel files in phpexcel
- Require_once 'classes/phpexcel/reader/excel2007.php ';
- Require_once 'classes/phpexcel/reader/excel5.php ';
- Include 'classes/phpexcel/iofactory. php ';
-
- Function arraytoexcel ($ data ){
- $ Objphpexcel = new phpexcel ();
- $ Objphpexcel-> setactivesheetindex (0 );
- $ Objphpexcel-> getactivesheet ()-> settitle ('firstsheet ');
- $ Objphpexcel-> getdefaultstyle ()-> getfont ()-> setname ('arial ');
- $ Objphpexcel-> getdefaultstyle ()-> getfont ()-> setsize (10 );
- // Add data
-
- $ I = 2;
- Foreach ($ data as $ line ){
- $ Objphpexcel-> getactivesheet ()-> setcellvalue ('A'. $ I, $ line ['from']);
- $ Objphpexcel-> getactivesheet ()-> getcell ('A'. $ I)-> setdatatype ('N ');
- $ Objphpexcel-> getactivesheet ()-> setcellvalue ('B'. $ I, $ line ['to']);
- $ Objphpexcel-> getactivesheet ()-> getcell ('B'. $ I)-> setdatatype ('N ');
- $ I ++;
- }
- $ Objwriter = phpexcel_iofactory: createwriter ($ objphpexcel, 'excel5 ');
- $ File = 'excel.xls ';
- $ Objwriter-> save ($ file );
- }
>>> For more php Tutorial content, please pay attention to the php programming section on this site. If you do not want to save it on the server and want to download it directly to the client after generation, you can add the following code when outputting the file without using $ objwriter-> save ($ file );
- Header ("pragma: public ");
- Header ("expires: 0 ");
- Header ("cache-control: must-revalidate, post-check = 0, pre-check = 0 ");
- Header ("content-type: application/force-download ");
- Header ("content-type: application/vnd. ms-execl ");
- Header ("content-type: application/octet-stream ");
- Header ("content-type: application/download ");
- Header ('content-disposition: attachment; filename = "excel.xls "');
- Header ("content-transfer-encoding: binary ");
- $ Objwriter-> save ('php: // output ');
Here is an example of reading the content of an excel file: the following code function exceltoarray is used to reorganize the content in an excel file and put it in an array.
- Require_once 'classes/phpexcel. php ';
- Require_once 'classes/phpexcel/iofactory. php ';
- Function exceltoarray ($ file ){
- $ Objreader = phpexcel_iofactory: createreader ('excel5 ');
- $ Objreader-> setreaddataonly (true );
- $ Objphpexcel = $ objreader-> load ($ file );
- $ Objworksheet = $ objphpexcel-> getactivesheet ();
- $ Highestrow = $ objworksheet-> gethighestrow ();
- $ Highestcolumn = $ objworksheet-> gethighestcolumn ();
- $ Highestcolumnindex = phpexcel_cell: columnindexfromstring ($ highestcolumn );
- $ Exceldata = array ();
- For ($ row = 2; $ row <= $ highestrow; ++ $ row ){
- For ($ col = 0; $ col <= $ highestcolumnindex; ++ $ col ){
- $ Exceldata [$ row] [] = $ objworksheet-> getcellbycolumnandrow ($ col, $ row)-> getvalue ();
- }
- }
- Return $ exceldata;
- }
|