Uploading to excel from mysql php. An easy way to transfer tabular data from PHP to Excel. Export data from MySQL to Excel in PHP

An object. But things are different if you need to generate a report in Excel format on PHP. And for this creation to function on UNIX-like systems. But, fortunately, everything is not so bad. And there are enough libraries for this. I chose PHPExcel. I've been working with this library for a couple of years now, and I'm satisfied. Since it is cross-platform, there are no portability issues.


PHPExcel allows you to import and export data to excel. Apply different design styles to reports. In general, everything is excellent. There is even the ability to work with formulas. It is only necessary to take into account that all work (reading and writing) must be carried out in encoding utf-8.


Installing the library

To work, you need PHP version 5.2.0 or higher. The following extensions are also required: 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:

  • Excel 2007;
  • Excel 97 and later;
  • PHPExcel Serialized Spreadshet;
  • HTML;

Importing data from PHP to Excel

Let's look at an example of forming a multiplication table.


// Connect the class to work with excel require_once("PHPExcel.php"); // Connect the class to output data in excel format require_once("PHPExcel/Writer/Excel5.php"); // Create an object of the PHPExcel class $xls = new PHPExcel(); // Set the index of the active sheet $xls->setActiveSheetIndex(0); // Get the active sheet $sheet = $xls->getActiveSheet(); // Sign the sheet $sheet->setTitle("Multiplication table"); // Insert text into cell A1 $sheet->setCellValue("A1", "Multiplication table"); $sheet->getStyle("A1")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID); $sheet->getStyle("A1")->getFill()->getStartColor()->setRGB("EEEEEE"); // Merge cells $sheet->mergeCells("A1:H1"); // Align text $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));

// Apply alignment $sheet->getStyleByColumnAndRow($i - 2, $j)->getAlignment()-> setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

) ) // Output HTTP headers 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"); // Output the contents of the file $objWriter = new PHPExcel_Writer_Excel5($xls);$objWriter->save("php://output");
  • Here the generated data will immediately be “spitted out” into the browser. However, if you need to save the file and not “throw it away” right away, 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 permissions. This applies to UNIX-like systems.

  • Let's look at three more useful instructions as an example:
    • $sheet->getColumnDimension("A")->setWidth(40)– sets the width of column “A” to 40 units; $sheet->getColumnDimension("B")->setAutoSize(true)– here column “B” will have an automatic width; $sheet->getRowDimension(4)->setRowHeight(20)– sets the height of the fourth line to 20 units. $sheet->getColumnDimension("B")->setAutoSize(true) Also pay attention to the following methods necessary for working with the report:
    • Methods for inserting data into a cell: setCellValue $sheet->getColumnDimension("A")->setWidth(40)().
  • ([$pCoordinate = "A1" [, $pValue = null [, $returnCell = false]]]) takes three parameters: the cell coordinate, the data to be output to the cell, and the third parameter is one of the boolean type constants:
    • true or
    • false(if you pass the value

As we can see, the above methods are paired. Therefore, we can work with cells using string or numeric representation of coordinates. Which of course is an additional advantage at work.

Generating a report using PHP in Excel

Very often there is a need to highlight some data in a report. Make a font highlight or apply a background fill frame to some cells, etc. This allows you to concentrate on the most important information (although it can also distract you). 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 - you cannot apply a style to several cells at the same time, but only to each one individually. But this does not create discomfort when developing web applications.


There are two ways to assign a style to a cell:

  • Apply method applyFromArray, class PHPExcel_Style. In method applyFromArray An array with the following parameters is passed:
    • fill- an array with fill parameters;
    • font- an array with font parameters;
    • borders- array with frame parameters;
    • alignment- array with alignment parameters;
    • number format- an array with parameters for the cell data presentation format;
    • protection- an array with cell protection parameters.
  • Use class method PHPExcel_Style for each style separately. For example, you can assign a font to a cell like this: $sheet->getStyle("A1")->getFont()->setName("Arial") .

Fill

Parameter value fill is an array with the following optional parameters:

  • type- fill type;
  • rotation- gradient angle;
  • startcolor- value in the form of an array with the initial color parameter in RGB format;
  • endcolor- value in the form of an array with the final color parameter in ARGB format;
  • color- value in the form of an array with the initial color parameter in RGB format.
Fill styles
FILL_NONE none
FILL_SOLID solid
FILL_GRADIENT_LINEAR linear
FILL_GRADIENT_PATH path
FILL_PATTERN_DARKDOWN darkDown
FILL_PATTERN_DARKGRAY darkGray
FILL_PATTERN_DARKGRID darkGrid
FILL_PATTERN_DARKHORIZONTAL darkHorizontal
FILL_PATTERN_DARKTRELLIS darkTrellis
FILL_PATTERN_DARKUP darkUp
FILL_PATTERN_DARKVERTICAL darkVertical
FILL_PATTERN_GRAY0625 gray0625
FILL_PATTERN_GRAY125 gray125
FILL_PATTERN_LIGHTDOWN lightDown
FILL_PATTERN_LIGHTGRAY lightGray
FILL_PATTERN_LIGHTGRID lightGrid
FILL_PATTERN_LIGHTHORIZONTAL lightHorizontal
FILL_PATTERN_LIGHTTRELLIS lightTrellis
FILL_PATTERN_LIGHTUP lightUp
FILL_PATTERN_LIGHTVERTICAL lightVertical
FILL_PATTERN_MEDIUMGRAY mediumGray
An example of specifying settings for filling:
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")).

Inserting Images

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

  • setPath([$pValue = "", [$pVerifyFile = $sheet->getColumnDimension("B")->setAutoSize(true)]]) this method takes two parameters. The first parameter specifies the path to the image file. And it makes sense to specify the second parameter if it is necessary to check the existence of a file (can take one of the values $sheet->getColumnDimension("B")->setAutoSize(true)– here column “B” will have an automatic width; $sheet->getRowDimension(4)->setRowHeight(20)).
  • setCoordinates([$pValue = "A1"])) принимает на вход один параметр в виде строки с координатой ячейки.!}
  • setOffsetX([$pValue = 0]) takes one parameter with the X offset value from the left edge of the cell.
  • setOffsetY([$pValue = 0]) takes one parameter with a Y offset value from the top edge of the cell.
  • setWorksheet([$pValue = null, [$pOverrideOld = $sheet->getRowDimension(4)->setRowHeight(20)]]) this method takes two parameters as input. The first is mandatory, the second is not. The first parameter is an instance of the active sheet object. If you pass as the value of the second parameter $sheet->getColumnDimension("B")->setAutoSize(true), then if the sheet was already assigned earlier, it will be overwritten and, accordingly, the image will be deleted.

The code demonstrating the algorithm for inserting an image is given 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) ...

This is what a report with an inserted image looks like:


Font

font an array is specified that contains the following optional parameters:

  • name- font name;
  • size- font size;
  • bold- highlight in bold;
  • italic- put it in italics;
  • underline- underlining style;
  • strike- cross out;
  • superScript- superscript;
  • subScript- subscript;
  • color
Underline styles
UNDERLINE_NONE No
UNDERLINE_DOUBLE double underscore
UNDERLINE_SINGLE single underscore
An example of specifying settings parameters for a 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

As a parameter value borders an array is specified that contains the following optional parameters:

  • frame type- (top|bootom|left|right|diagonal|diagonaldirection);
  • style- frame style;
  • color- value in the form of an array with a color parameter in RGB format.
Line stylesAn example of specifying settings parameters for a 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

Parameter value alignment is an array that takes four optional parameters as input:

  • horizontal- horizontal alignment constant;
  • vertical- vertical alignment constant;
  • rotation- text rotation angle;
  • wrap- allow text wrapping;
  • shrinkToFit- whether to change the font size when the text goes beyond the cell area;
  • indent- indentation from the left edge.
Horizontal alignmentVertical alignment
VERTICAL_BOTTOM along the bottom edge
VERTICAL_TOP along the top edge
VERTICAL_CENTER in the center
VERTICAL_JUSTIFY in height
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)

$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

Parameter number format is an array that includes only one parameter: code- cell data format.


List of possible formats
FORMAT_GENERAL General
FORMAT_TEXT @
FORMAT_NUMBER 0
FORMAT_NUMBER_00 0.00
FORMAT_NUMBER_COMMA_SEPARATED1 #,##0.00
FORMAT_NUMBER_COMMA_SEPARATED2 #,##0.00_-
FORMAT_PERCENTAGE 0%
FORMAT_PERCENTAGE_00 0.00%
FORMAT_DATE_YYYYMMDD2 yyyy-mm-dd
FORMAT_DATE_YYYYMMDD yy-mm-dd
FORMAT_DATE_DDMMYYYY dd/mm/yy
FORMAT_DATE_DMYSLASH d/m/y
FORMAT_DATE_DMYMINUS d-m-y
FORMAT_DATE_DMMINUS d-m
FORMAT_DATE_MYMINUS m-y
FORMAT_DATE_XLSX14 mm-dd-yy
FORMAT_DATE_XLSX15 d-mmm-yy
FORMAT_DATE_XLSX16 d-mmm
FORMAT_DATE_XLSX17 mmm-yy
FORMAT_DATE_XLSX22 m/d/yy h:mm
FORMAT_DATE_DATETIME d/m/y h:mm
FORMAT_DATE_TIME1 h:mm AM/PM
FORMAT_DATE_TIME2 h:mm:ss AM/PM
FORMAT_DATE_TIME3 h:mm
FORMAT_DATE_TIME4 h:mm:ss
FORMAT_DATE_TIME5 mm:ss
FORMAT_DATE_TIME6 h:mm:ss
FORMAT_DATE_TIME7 i:s.S
FORMAT_DATE_TIME8 h:mm:ss
FORMAT_DATE_YYYYMMDDSLASH yy/mm/dd; @
FORMAT_CURRENCY_USD_SIMPLE "$"#,##0.00_-;@
FORMAT_CURRENCY_USD $#,##0_-
FORMAT_CURRENCY_EUR_SIMPLE [$EUR ]#,##0.00_-
Example setting for cell data format: array("code" => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);

Or you can use the method:

$PHPExcel_Style->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);

Cell protection

As a parameter value protection acts as an array that contains two optional parameters:

  • locked- protect the cell;
  • hidden- hide formulas.
Example of setting parameters 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 will apply a design style to the table cells, but we will do this in two ways. The first method is to create an array of settings, which we will pass as a parameter to the method applyFromArray, class PHPExcel_Style.


$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 will apply the style we created to the excel cells.

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

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


//Set the alignment $sheet->getStyleByColumnAndRow($i - 2, $j)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); // Set the font $sheet->getStyleByColumnAndRow($i - 2, $j)->getFont()->setName("Arial"); // Apply a fill $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 need to apply the style repeatedly, then the first method is better; in other cases, it is better to stick to the second. To get an object (class instance PHPExcel_Style) cells responsible for the style, you must use one of the following methods:

  • getStyleByColumnAndRow([$pColumn = 0 [, $pRow = 1]]) – used if you need to refer to a cell by numerical coordinates. The method must be passed two parameters in the form of cell column and row numbers;
  • getStyle() – used to access the string coordinate of a cell. The method requires passing one parameter, this is a string representation of the coordinate.

Adding comments

I think that it is not often that someone uses the opportunity to add comments to cells, but this is purely my personal opinion, but such an opportunity exists. Adding a comment to a cell is quite simple, as you can see in the example below:


... // Font styles $fBold = array("name" => "Tahoma", "size" => 10, "bold" => true); $fNormal = array("name" => "Tahoma", "size" => 10); $richText = $sheet->getComment("B2")->getText(); $richText->createTextRun("Lorem ipsum")->getFont()-> applyFromArray($fNormal); $richText->createTextRun("dolor sit")->getFont()->applyFromArray($fBold); $richText->createTextRun(" amet consectetuer")->getFont()-> applyFromArray($fNormal); // Comment field width $sheet->getComment("B2")->setWidth("250"); // Height of the comment field $sheet->getComment("B2")->setHeight("25"); ...

It should be noted that when calling the method again createTextRun() the new comment will be added to the existing one, rather than replacing it. It should be noted that this method returns an object of the PHPExcel_RichText_Run class, which has methods for setting and getting font parameters:

  • getFont() – returns a class object for working with PHPExcel_Style_Font fonts.
  • setFont([$pFont = null]))]) – this method requires passing an object of the PHPExcel_Style_Font class as a parameter.

That's the kind of comment we should get.

For many, when working with PHP in conjunction with MySQL There is such a need as exporting data from the database to xls format, so that people who need this data process it in Excel or it is simply convenient for users to view this data. Recently I had such a need and today I will tell you how this matter can be implemented.

I’ll say right away that this method is quite simple, but the data is uploaded normally.

To begin with, I will give an example of the final xls file; in Excel, the upload will look something like this:

In other words, no images or styles will be uploaded, only column headers and the data themselves.

Before I came to exactly this option for uploading, I tried uploading in csv format, but it turned out a little clumsily, then I tried to draw a table and save it with the xls extension, it also turned out to be some kind of nonsense, the method that I will now describe completely suited me , and now I will share it with you.

To begin with, I’ll give you all the code, which I commented as much as possible, you can select it and save it with the php extension and try it, just don’t forget to specify the settings for connecting to the database.

Export data from MySQL to Excel in PHP

And so that you understand what data I am uploading, I will give an example of a simple table in the database ( I have its name test):

Test table:

id firstname name
1 Ivanov Ivan
2 Petrov Peter
2 Petrov2 Peter2
xlsData = pack("ssssss", 0x809, 0x08, 0x00,0x10, 0x0, 0x0);

) // If the number function RecNumber($row, $col, $value)( $this->xlsData .= pack("sssss", 0x0203, 14, $row, $col, 0x00); $this->xlsData . = pack("d", $value); return; ) //If the text function RecText($row, $col, $value)( $len = strlen($value); $this->xlsData .= pack(" s*", 0x0204, 8 + $len, $row, $col, 0x00, $len); $this->xlsData .= $value; return; ) // Insert a number function InsertNumber($value)( if ($ this->countCol == $this->totalCol) ( $this->countCol = 0; $this->countRow++; ) $this->RecNumber($this->countRow, $this->countCol, $value); $this->countCol++; return; ) // Insert text function InsertText($value)( if ($this->countCol == $this->totalCol) ( $this->countCol = 0; $this->countRow++; ) $this->RecText($this->countRow, $this->countCol, $value); $this->countCol++; return; // Go to new line function GoNewLine())( $this->countCol = 0 ; $this->countRow++; return; ) //End of data function EndData() ( $this->xlsData .= pack("ss", 0x0A, 0x00); return;) // Save the file function SaveFile($fileName)( $this->fileName = $fileName; $this->SendFile(); ) // Send the file function SendFile())( $this->EndData(); header (" Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT"); header ("Cache-Control: no-store, no-cache, must-revalidate"); header (" Pragma: no-cache"); header ("Content-type: application/x-msexcel"); header ("Content-Disposition: attachment; fileName=$this->fileName.xls"); print $this->xlsData ; ) ) ) if(isset($_GET["id"])) ( //filter the data $id = mysql_real_escape_string(stripslashes(trim(htmlspecialchars($_GET["id"],ENT_QUOTES)))); $filename = "File_with_id_".$id; // set the file name $excel = new ExportToExcel(); // create an instance of the class $sql="SELECT * FROM test.test where id = $id";//query to the database $rez= mysql_query($sql); $excel->InsertText("Identifier"); $excel->InsertText("Last Name"); $excel->InsertText("Name"); $excel->GoNewLine(); row=mysql_fetch_assoc($rez))( $excel->InsertNumber($row["id"]); $excel->InsertText($row["firstname"]);$excel->InsertText($row["name"]); $excel->GoNewLine();.

In order to check the functionality of this code, taking into account the fact that you have configured a connection to the database and created a similar table, you can send the following request:

Http://your_site/file_name. php?id=2

And you should unload two lines with id equal to 2.

And now anyone you allow to upload data can easily export it to their local computer via the web interface. This method is convenient both for corporate users, if you are developing an application for your organization, and for users of your website on the Internet. I hope this method helped you. Good luck!

.
The method presented in that note is indeed very simple, but may not always be convenient.
There are many other ways to transfer tabular data from PHP to Excel, I will describe the one that seemed to me the most simple and functional. It should be especially noted that I am not talking about generating an xls file, but only suggesting that the user open the received data using Excel so that users who are not experienced in programming will not notice the forgery.

So, the first thing you need to do is place on our page a link to a script that generates the following headers:
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/x-msexcel");
header("Content-Disposition: attachment; filename=\"" . iconv("UTF-8", "CP1251", $object->getFileName()) . "\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $object->getFileSize());

$object is a spherical object in a vacuum, which each reader can implement as he or she likes. The purpose of getFileName() and getFileSize() getters is clear from their names. It’s worth highlighting one non-obvious nuance here (thanks for reminding me of this) - getFileName() can of course return any file name, but if you want the browser to offer to open the received content in Excel, then the file extension should be xls.
I haven’t said anything new yet, all this was invented before me, however, like what will be described below.
As was rightly noted in the comments to the article, Excel works much faster with XML. But the most important advantage, perhaps, is not speed, but much broader capabilities. I won’t go deeper into the weeds, but will just give a simple example and a link to a detailed description of all the tags.

So, after the headers are generated, we need to give the actual data to the user. I usually wrap table generation in a separate method:
echo $object->getContent();

And I generate the table using Smarty:

(foreach from=$data.header item=caption) ($caption.columnName)(/foreach)(foreach from=$data.content item=row) (foreach from=$row item=col) ($col)(/foreach)(/foreach)

As you can see from the code, the $data array is passed to the template, containing two arrays - the table title line and the data itself.
It is worth noting that using a template engine only to generate XML is somewhat expensive, and XML can be obtained in many other ways. In my particular case, XML generation is just a small bonus in a large project where a template engine is indispensable.

As an example, I gave a simple table; if desired, you can manipulate a much larger number of attributes. This is especially nice considering that no third party libraries are required for implementation.
The described method has been working on one project for several years and not a single user has yet suspected that the data he opens is not an MS Office document.

You can read more about the XML structure used in MS Excel in

.
The method presented in that note is indeed very simple, but may not always be convenient.
There are many other ways to transfer tabular data from PHP to Excel, I will describe the one that seemed to me the most simple and functional. It should be especially noted that I am not talking about generating an xls file, but only suggesting that the user open the received data using Excel so that users who are not experienced in programming will not notice the forgery.

So, the first thing you need to do is place on our page a link to a script that generates the following headers:
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/x-msexcel");
header("Content-Disposition: attachment; filename=\"" . iconv("UTF-8", "CP1251", $object->getFileName()) . "\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $object->getFileSize());

$object is a spherical object in a vacuum, which each reader can implement as he or she likes. The purpose of getFileName() and getFileSize() getters is clear from their names. It’s worth highlighting one non-obvious nuance here (thanks to savostin for reminding me of this) - getFileName() can of course return any file name, but if you want the browser to offer to open the received content in Excel, then the file extension should be xls.
I haven’t said anything new yet, all this was invented before me, however, like what will be described below.
As was rightly noted in the comments to the post about xls generation in PHP, Excel works much faster with XML. But the most important advantage, perhaps, is not speed, but much broader capabilities. I won’t go deeper into the weeds, but will just give a simple example and a link to a detailed description of all the tags.

So, after the headers are generated, we need to give the actual data to the user. I usually wrap table generation in a separate method:
echo $object->getContent();

And I generate the table using Smarty:

(foreach from=$data.header item=caption) ($caption.columnName)(/foreach)(foreach from=$data.content item=row) (foreach from=$row item=col) ($col)(/foreach)(/foreach)

As you can see from the code, the $data array is passed to the template, containing two arrays - the table title line and the data itself.
It is worth noting that using a template engine only to generate XML is somewhat expensive, and XML can be obtained in many other ways. In my particular case, XML generation is just a small bonus in a large project where a template engine is indispensable.

As an example, I gave a simple table; if desired, you can manipulate a much larger number of attributes. This is especially nice considering that no third party libraries are required for implementation.
The described method has been working on one project for several years and not a single user has yet suspected that the data he opens is not an MS Office document.

You can read more about the XML structure used in MS Excel in



Have questions?

Report a typo

Text that will be sent to our editors: