📜 ⬆️ ⬇️

Processing and processing reports in Excel in PHP

Not rarely, when developing a project, it becomes necessary to form reporting statistics. If the project is developed in Delphi , C # or for example, in C ++ and under Windows , then there are no problems. Just need to use the COM object. But things are different if you need to generate a report in excel format for PHP . And for this creation to function on UNIX-like systems. But, fortunately, not so bad. And there are enough libraries for this. I stopped my choice on PHPExcel . I have been working with this library for a couple of years now and am satisfied. Since it is cross-platform, there are no problems with portability.
PHPExcel allows you to import and export data to excel. Apply different styles to reports. In general, everything is on top. There is even the possibility of working with formulas (I have not tried it myself). Just remember that all work (read and write) must be in the utf-8 encoding.

Library installation
A version of PHP 5.2.0 or higher is required. The following extensions are also needed: php_zip, php_xml and php_gd2. You can download the library from here .

Using the PHPExcel library, you can write data in the following formats:


')

Import data from PHP to Excel


Consider an example of the formation of the multiplication table.

//      excel require_once('PHPExcel.php'); //        excel require_once('PHPExcel/Writer/Excel5.php'); //    PHPExcel $xls = new PHPExcel(); //     $xls->setActiveSheetIndex(0); //    $sheet = $xls->getActiveSheet(); //   $sheet->setTitle(' '); //     A1 $sheet->setCellValue("A1", ' '); $sheet->getStyle('A1')->getFill()->setFillType( PHPExcel_Style_Fill::FILL_SOLID); $sheet->getStyle('A1')->getFill()->getStartColor()->setRGB('EEEEEE'); //   $sheet->mergeCells('A1:H1'); //   $sheet->getStyle('A1')->getAlignment()->setHorizontal( PHPExcel_Style_Alignment::HORIZONTAL_CENTER); for ($i = 2; $i < 10; $i++) { for ($j = 2; $j < 10; $j++) { //    $sheet->setCellValueByColumnAndRow( $i - 2, $j, $i . "x" .$j . "=" . ($i*$j)); //   $sheet->getStyleByColumnAndRow($i - 2, $j)->getAlignment()-> setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); } } 

Next we need to get our * .xls file. Here you can go two ways. If we assume you have an online store, and the customer wants to download the price list, then it would be better to resort to this conclusion:

 //  HTTP- header ( "Expires: Mon, 1 Apr 1974 05:00:00 GMT" ); header ( "Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT" ); header ( "Cache-Control: no-cache, must-revalidate" ); header ( "Pragma: no-cache" ); header ( "Content-type: application/vnd.ms-excel" ); header ( "Content-Disposition: attachment; filename=matrix.xls" ); //    $objWriter = new PHPExcel_Writer_Excel5($xls); $objWriter->save('php://output'); 



Here, the generated data immediately “spit out” in the browser. However, if you need to save the file and not “discard” it immediately, then you do not need to output HTTP headers and instead of “php: // output” you should specify the path to your file. Remember that the directory in which the file is supposed to be created must have write access. This applies to UNIX-like systems.
Consider another example of three useful instructions:



Also notice these methods here: setCellValue and setCellValueByColumnAndRow .



That is, you can access cells in two different ways. Which is very convenient.

Making a report using PHP in Excel


It is often necessary to highlight some data in a report. Make a font selection or apply a frame with a background fill for some cells, etc. What allows you to concentrate on the most important information (although it may conversely distract). For these purposes, the PHPExcel library has a whole set of styles that can be applied to cells in excel. Of course, there is a small “minus” in this library - it is impossible to apply the style to several cells at the same time, but only to each individually. But this does not create discomfort when developing web applications.
You can assign a style to a cell in two ways:



Fill


The value of the fill parameter is an array with the following optional parameters:



Fill styles

FILL_NONEnone
FILL_SOLIDsolid
FILL_GRADIENT_LINEARlinear
FILL_GRADIENT_PATHpath
FILL_PATTERN_DARKDOWNdarkDown
FILL_PATTERN_DARKGRAYdarkGray
FILL_PATTERN_DARKGRIDdarkGrid
FILL_PATTERN_DARKHORIZONTALdarkHorizontal
FILL_PATTERN_DARKTRELLISdarkTrellis
FILL_PATTERN_DARKUPdarkUp
FILL_PATTERN_DARKVERTICALdarkVertical
FILL_PATTERN_GRAY0625gray0625
FILL_PATTERN_GRAY125gray125
FILL_PATTERN_LIGHTDOWNlightDown
FILL_PATTERN_LIGHTGRAYlightGray
FILL_PATTERN_LIGHTGRIDlightGrid
FILL_PATTERN_LIGHTHORIZONTALlightHorizontal
FILL_PATTERN_LIGHTTRELLISlightTrellis
FILL_PATTERN_LIGHTUPlightUp
FILL_PATTERN_LIGHTVERTICALlightVertical
FILL_PATTERN_MEDIUMGRAYmediumGray

An example of specifying settings for the fill:

 array( 'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR, 'rotation' => 0, 'startcolor' => array( 'rgb' => '000000' ), 'endcolor' => array( 'argb' => 'FFFFFFFF' ), 'color' => array( 'rgb' => '000000' ) ); 

Or you can use the following methods:
$ PHPExcel_Style-> getFill () -> setFillType (PHPExcel_Style_Fill :: FILL_GRADIENT_LINEAR);
$ PHPExcel_Style-> getFill () -> setRotation (0);
$ PHPExcel_Style-> getFill () -> getStartColor () -> applyFromArray (array ('rgb' => 'C2FABD'));
$ PHPExcel_Style-> getFill () -> getEndColor () -> applyFromArray (array ('argb' => 'FFFFFFFF')).

Insert images


Quite rarely, but it is useful to insert an image into a report. This could be a logo, a scheme, etc. To work we need the following methods:


Code showing the image insertion algorithm is shown below:
 ... $sheet->getColumnDimension('B')->setWidth(40); $imagePath = dirname ( __FILE__ ) . '/excel.png'; if (file_exists($imagePath)) { $logo = new PHPExcel_Worksheet_Drawing(); $logo->setPath($imagePath); $logo->setCoordinates("B2"); $logo->setOffsetX(0); $logo->setOffsetY(0); $sheet->getRowDimension(2)->setRowHeight(190); $logo->setWorksheet($sheet); } ... 


Here is the report with the image inserted:


Font


The value of the font parameter is an array that contains the following optional parameters:


Underline styles

UNDERLINE_NONEnot
UNDERLINE_DOUBLEdouble underscore
UNDERLINE_SINGLEsingle underscore

Example of specifying settings for the font:

 array( 'name' => 'Arial', 'size' => 12, 'bold' => true, 'italic' => false, 'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE, 'strike' => false, 'superScript' => false, 'subScript' => false, 'color' => array( 'rgb' => '808080' ) ); 

Or use the following methods:
$ PHPExcel_Style-> getFont () -> setName ('Arial');
$ PHPExcel_Style-> getFont () -> setBold (true);
$ PHPExcel_Style-> getFont () -> setItalic (false);
$ PHPExcel_Style-> getFont () -> setSuperScript (false);
$ PHPExcel_Style-> getFont () -> setSubScript (false);
$ PHPExcel_Style-> getFont () -> setUnderline (PHPExcel_Style_Font :: UNDERLINE_DOUBLE);
$ PHPExcel_Style-> getFont () -> setStrikethrough (false);
$ PHPExcel_Style-> getFont () -> getColor () -> applyFromArray (array ('rgb' => '808080'));
$ PHPExcel_Style-> getFont () -> setSize (12).

Frame


The value of the borders parameter is an array that contains the following optional parameters:


Line styles

BORDER_NONEnot
BORDER_DASHDOTdotted with dot
BORDER_DASHDOTDOTdotted with two dots
BORDER_DASHEDdotted
BORDER_DOTTEDpoint
BORDER_DOUBLEdouble
BORDER_HAIRhairline
BORDER_MEDIUMaverage
BORDER_MEDIUMDASHDOTdotted with dot
BORDER_MEDIUMDASHDOTDOTthick dotted line with two points
BORDER_MEDIUMDASHEDthick dotted
BORDER_SLANTDASHDOTslant dotted with dot
BORDER_THICKthickened
BORDER_THINthin

Example of specifying settings for the frame:

 array( 'bottom' => array( 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, 'color' => array( ' rgb' => '808080' ) ), 'top' => array( 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, 'color' => array( 'rgb' => '808080' ) ) ); 

You can also resort to using the following methods:
$ PHPExcel_Style-> getBorders () -> getLeft () -> applyFromArray (array ('style' => PHPExcel_Style_Border :: BORDER_DASHDOT, 'color' => array ('rgb' => '808080'))));
$ PHPExcel_Style-> getBorders () -> getRight () -> applyFromArray (array ('style' => PHPExcel_Style_Border :: BORDER_DASHDOT, 'color' => array ('rgb' => '808080'))));
$ PHPExcel_Style-> getBorders () -> getTop () -> applyFromArray (array ('style' => PHPExcel_Style_Border :: BORDER_DASHDOT, 'color' => array ('rgb' => '808080'))));
$ PHPExcel_Style-> getBorders () -> getBottom () -> applyFromArray (array ('style' => PHPExcel_Style_Border :: BORDER_DASHDOT, 'color' => array ('rgb' => '808080'))));
$ PHPExcel_Style-> getBorders () -> getDiagonal () -> applyFromArray (array ('style' => PHPExcel_Style_Border :: BORDER_DASHDOT, 'color' => array ('rgb' => '808080'))));
$ PHPExcel_Style-> getBorders () -> setDiagonalDirection (array ('style' => PHPExcel_Style_Border :: BORDER_DASHDOT, 'color' => array ('rgb' => '808080'))).

Alignment


The value of the alignment parameter is an array that accepts four optional parameters as input:


Horizontal alignment

HORIZONTAL_GENERALthe main
HORIZONTAL_LEFTon the left
HORIZONTAL_RIGHTright hand
HORIZONTAL_CENTERcentered
HORIZONTAL_CENTER_CONTINUOUScentered selection
HORIZONTAL_JUSTIFYacross the width

Vertical Alignment

VERTICAL_BOTTOMbottom edge
VERTICAL_TOPalong the top edge
VERTICAL_CENTERcentered
VERTICAL_JUSTIFYby height

An example of alignment style settings:

 array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'rotation' => 0, 'wrap' => true, 'shrinkToFit' => false, 'indent' => 5 ) 

And you can use the following methods:
$ PHPExcel_Style-> getAlignment () -> setHorizontal (PHPExcel_Style_Alignment :: HORIZONTAL_CENTER);
$ PHPExcel_Style-> getAlignment () -> setVertical (PHPExcel_Style_Alignment :: VERTICAL_JUSTIFY);
$ PHPExcel_Style-> getAlignment () -> setTextRotation (10);
$ PHPExcel_Style-> getAlignment () -> setWrapText (true);
$ PHPExcel_Style-> getAlignment () -> setShrinkToFit (false);
$ PHPExcel_Style-> getAlignment () -> setIndent (5).

Data presentation format


The numberformat parameter is an array that includes only one parameter: code is the data format of the cell.
List of possible formats

FORMAT_GENERALGeneral
FORMAT_TEXT@
FORMAT_NUMBER0
FORMAT_NUMBER_000.00
FORMAT_NUMBER_COMMA_SEPARATED1#, ## 0.00
FORMAT_NUMBER_COMMA_SEPARATED2#, ## 0.00_-
FORMAT_PERCENTAGE0%
FORMAT_PERCENTAGE_000.00%
FORMAT_DATE_YYYYMMDD2yyyy-mm-dd
FORMAT_DATE_YYYYMMDDyy-mm-dd
FORMAT_DATE_DDMMYYYYdd / mm / yy
FORMAT_DATE_DMYSLASHd / m / y
FORMAT_DATE_DMYMINUSdmy
FORMAT_DATE_DMMINUSdm
FORMAT_DATE_MYMINUSmy
FORMAT_DATE_XLSX14mm-dd-yy
FORMAT_DATE_XLSX15d-mmm-yy
FORMAT_DATE_XLSX16d-mmm
FORMAT_DATE_XLSX17mmm-yy
FORMAT_DATE_XLSX22m / d / yy h: mm
FORMAT_DATE_DATETIMEd / m / yh: mm
FORMAT_DATE_TIME1h: mm AM / PM
FORMAT_DATE_TIME2h: mm: ss AM / PM
FORMAT_DATE_TIME3h: mm
FORMAT_DATE_TIME4h: mm: ss
FORMAT_DATE_TIME5mm: ss
FORMAT_DATE_TIME6h: mm: ss
FORMAT_DATE_TIME7i: sS
FORMAT_DATE_TIME8h: mm: ss
FORMAT_DATE_YYYYMMDDSLASHyy / mm / dd; @
FORMAT_CURRENCY_USD_SIMPLE"$" #, ## 0.00 _-; @
FORMAT_CURRENCY_USD$ #, ## 0_-
FORMAT_CURRENCY_EUR_SIMPLE[$ EUR] #, ## 0.00_-

Example setup for cell data format:

 array( 'code' => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE ); 

And you can use the method:
$ PHPExcel_Style-> getNumberFormat () -> setFormatCode (PHPExcel_Style_NumberFormat :: FORMAT_CURRENCY_EUR_SIMPLE);

Cell protection


The value of the protection parameter is an array, which contains two optional parameters:


Parameter setting example for cell protection:

 array( 'locked' => true, 'hidden' => false ); 

Or use the following methods:
$ PHPExcel_Style-> getProtection () -> setLocked (true);
$ PHPExcel_Style-> getProtection () -> setHidden (false);
Now we know what style settings there are and what parameters each style has. Now we apply a layout style to the cells of the table, but we will do this using two methods. The first method is to create an array of settings, which we pass as the parameter to the applyFromArray method, PHPExcel_Style class.

 $style = array( 'font' => array( 'name' => 'Arial', ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array ( 'rgb' => 'C2FABD' ) ), 'alignment' => array ( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ) ); 


Next we apply the style we created to the excel cells.

 $sheet->getStyleByColumnAndRow($i - 2, $j)->applyFromArray($style); 

Now apply the same style, but using a different technique.

 //  $sheet->getStyleByColumnAndRow($i - 2, $j)->getAlignment()->setHorizontal( PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //   $sheet->getStyleByColumnAndRow($i - 2, $j)->getFont()->setName('Arial'); //   $sheet->getStyleByColumnAndRow($i - 2, $j)->getFill()-> setFillType(PHPExcel_Style_Fill::FILL_SOLID); $sheet->getStyleByColumnAndRow($i - 2, $j)->getFill()-> getStartColor()->applyFromArray(array('rgb' => 'C2FABD')); 

Here's what we got:

If you want to apply the style many times, then the first method is better, in the other case, it is better to stay on the second. To obtain an object (an instance of the class PHPExcel_Style ) of the cell responsible for the style, you must use one of the following methods:


Reading data from Excel


Generating reports and applying styles to them is of course excellent. But the possibilities of the PHP Excel library do not end there. Well, let's look at what she is still capable of. And it is also capable of reading data from * .xls / * .xlsx files.
Using the PHPExcel library, you can read the following formats:


To work we need objects of two classes:


For demonstration we will display data from the table with information about cars.

An example of reading the file is presented below:

 require_once ('PHPExcel/IOFactory.php'); //   $xls = PHPExcel_IOFactory::load('xls.xls'); //     $xls->setActiveSheetIndex(0); //    $sheet = $xls->getActiveSheet(); 


First option
 ... echo "<table>"; //        $rowIterator = $sheet->getRowIterator(); foreach ($rowIterator as $row) { //          $cellIterator = $row->getCellIterator(); echo "<tr>"; foreach ($cellIterator as $cell) { echo "<td>" . $cell->getCalculatedValue() . "</td>"; } echo "</tr>"; } echo "</table>"; 


Second option

 ... echo "<table>"; for ($i = 1; $i <= $sheet->getHighestRow(); $i++) { echo "<tr>"; $nColumn = PHPExcel_Cell::columnIndexFromString( $sheet->getHighestColumn()); for ($j = 0; $j < $nColumn; $j++) { $value = $sheet->getCellByColumnAndRow($j, $i)->getValue(); echo "<td>$value</td>"; } echo "</tr>"; } echo "</table>"; 


In the first variant, we read data from cells using iterators. And in the second, we use index addressing to access and retrieve data from the cells of the paper. You can get data on the number of rows and columns using the following methods of the PHPExcel_Worksheet class:


And also, we cannot do without the help of the columnIndexFromString method, which is part of the PHPExcel_Cell class. This method allows you to determine the column index by its symbolic representation.
With the help of the demonstrated capabilities, you can generate and read any reports in the form of files, excel format. And also almost all possible methods for working with styles were demonstrated.

Source: https://habr.com/ru/post/245233/


All Articles