{"id":128319,"date":"2022-09-23T04:58:12","date_gmt":"2022-09-23T04:58:12","guid":{"rendered":"https:\/\/phppot.com\/?p=17407"},"modified":"2022-09-23T04:58:12","modified_gmt":"2022-09-23T04:58:12","slug":"php-excel-export-code-data-to-file","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/09\/23\/php-excel-export-code-data-to-file\/","title":{"rendered":"PHP Excel Export Code (Data to File)"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1666666666667\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on September 23rd, 2022.<\/div>\n<p>Export data to an excel file is mainly used for taking a backup. When taking database backup, excel format is a convenient one to read and manage easily. For some applications exporting data is important to take a backup or an offline copy of the server database.<\/p>\n<p>This article shows how to export data to excel using PHP. There are many ways to implement this functionality. We have already seen an <a href=\"https:\/\/phppot.com\/php\/database-data-export-to-excel-file-using-php\/\">example of data export from MySQL<\/a>.<\/p>\n<p><strong>This article uses the PHPSpreadSheet library for implementing PHP excel export.<\/strong><\/p>\n<p>It is a popular library that supports reading, and writing excel files. It will smoothen the excel <a href=\"https:\/\/phppot.com\/php\/how-to-handle-csv-with-php-read-write-import-export-with-database\/\">import-export operations<\/a> through its built-in functions.<\/p>\n<p>The complete example in this article will let create your own export tool or your application.<br \/><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-19505\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-excel-export-550x471.jpg\" alt=\"php excel export\" width=\"550\" height=\"471\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-excel-export-550x471.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-excel-export-300x257.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-excel-export-768x658.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-excel-export.jpg 916w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>About this Example<\/h2>\n<p>It will show a minimal interface with the list of database records and an \u201cExport to Excel\u201d button. By clicking this button, it will call the custom ExportService created for this example.<\/p>\n<p>This service instantiates the PHPSpreadsheet library class and sets the column header and values. Then it creates a writer object by setting the PHPSpreadsheet instance to output the data to excel.<\/p>\n<p>Follow the below steps to let this example run in your environment.<\/p>\n<ol>\n<li>Create and set up the database with data exported to excel.<\/li>\n<li>Download the code at the end of this article and configure the database.<\/li>\n<li>Add PHPSpreadSheet library and other dependencies into the application.<\/li>\n<\/ol>\n<p>We have already used the <a href=\"https:\/\/phppot.com\/php\/extract-images-from-url-in-excel-with-php-using-phpspreadsheet\/\">PHPSpreadsheet library to store extracted image URLs<\/a>.<\/p>\n<h2>1) Create and set up the database with data exported to excel<\/h2>\n<p>Create a database named \u201cdb_excel_export\u201d and import the below SQL script into it.<\/p>\n<p class=\"code-heading\">structure.sql<\/p>\n<pre class=\"prettyprint\"><code class=\"language-sql\">--\n-- Table structure for table `tbl_products`\n-- CREATE TABLE `tbl_products` ( `id` int(8) NOT NULL, `name` varchar(255) NOT NULL, `price` double(10,2) NOT NULL, `category` varchar(255) NOT NULL, `product_image` text NOT NULL, `average_rating` float(3,1) NOT NULL\n); --\n-- Dumping data for table `tbl_products`\n-- INSERT INTO `tbl_products` (`id`, `name`, `price`, `category`, `product_image`, `average_rating`) VALUES\n(1, 'Tiny Handbags', 100.00, 'Fashion', 'gallery\/handbag.jpeg', 5.0),\n(2, 'Men\\'s Watch', 300.00, 'Generic', 'gallery\/watch.jpeg', 4.0),\n(3, 'Trendy Watch', 550.00, 'Generic', 'gallery\/trendy-watch.jpeg', 4.0),\n(4, 'Travel Bag', 820.00, 'Travel', 'gallery\/travel-bag.jpeg', 5.0),\n(5, 'Plastic Ducklings', 200.00, 'Toys', 'gallery\/ducklings.jpeg', 4.0),\n(6, 'Wooden Dolls', 290.00, 'Toys', 'gallery\/wooden-dolls.jpeg', 5.0),\n(7, 'Advanced Camera', 600.00, 'Gadget', 'gallery\/camera.jpeg', 4.0),\n(8, 'Jewel Box', 180.00, 'Fashion', 'gallery\/jewel-box.jpeg', 5.0),\n(9, 'Perl Jewellery', 940.00, 'Fashion', 'gallery\/perls.jpeg', 5.0); --\n-- Indexes for dumped tables\n-- --\n-- Indexes for table `tbl_products`\n--\nALTER TABLE `tbl_products` ADD PRIMARY KEY (`id`); --\n-- AUTO_INCREMENT for dumped tables\n-- --\n-- AUTO_INCREMENT for table `tbl_products`\n--\nALTER TABLE `tbl_products` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;\n<\/code><\/pre>\n<h2>2) Download the code and configure the database<\/h2>\n<p>The source code contains the following files. This section explains the database configuration.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-19496\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/excel-export-file-structure.jpg\" alt=\"excel export file structure\" width=\"199\" height=\"205\"><\/p>\n<p>Once you download the excel export code from this page, you can find&nbsp;<em>DataSource.php<\/em> file in the <em>lib<\/em> folder. Open it and configure the database details in it as below.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php class DataSource\n{ const HOST = 'localhost'; const USERNAME = 'root'; const PASSWORD = ''; const DATABASENAME = 'db_excel_export'; ... ...\n?&gt;\n<\/code><\/pre>\n<h2>3) Add PHPSpreadSheet library and other dependencies into the application<\/h2>\n<p>When you <a href=\"https:\/\/phpspreadsheet.readthedocs.io\/en\/latest\/\" target=\"_blank\" rel=\"noopener\">see the PHPSpreadsheet documentation<\/a>, it provides an easy to follow installation steps.<\/p>\n<p>It gives the composer command to add the PHPSpreadsheet and related dependencies into the application.<\/p>\n<pre class=\"prettyprint\"><code>composer require phpoffice\/phpspreadsheet\n<\/code><\/pre>\n<h3>For PHP version 7<\/h3>\n<p>Add the below specification to the composer.json file.<\/p>\n<pre class=\"prettyprint\"><code>{ \"require\": { \"phpoffice\/phpspreadsheet\": \"^1.23\" }, \"config\": { \"platform\": { \"php\": \"7.3\" } }\n}\n<\/code><\/pre>\n<p>then run<\/p>\n<pre class=\"prettyprint\"><code>composer update\n<\/code><\/pre>\n<p><strong>Note:<\/strong> PHPSpreadsheet requires at least PHP 7.3 version.<\/p>\n<h2>How it works<\/h2>\n<h3>Simple interface with export option<\/h3>\n<p>This page fetches the data from the MySQL database and <a href=\"https:\/\/phppot.com\/jquery\/using-jqgrid-control-with-php\/\">displays it in a grid form<\/a>. Below the data grid, this page shows an \u201cExcel Export\u201d button.<\/p>\n<p>By clicking this button the action parameter is sent to the URL to call the excel export service in PHP.<\/p>\n<p class=\"code-heading\">index.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php-template\">&lt;?php\nrequire_once __DIR__ . '\/lib\/Post.php';\n$post = new post();\n$postResult = $post-&gt;getAllPost();\n$columnResult = $post-&gt;getColumnName();\nif (! empty($_GET[\"action\"])) { require_once __DIR__ . '\/lib\/ExportService.php'; $exportService = new ExportService(); $result = $exportService-&gt;exportExcel($postResult, $columnResult);\n}\n?&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"&gt;\n&lt;link href=\".\/style.css\" type=\"text\/css\" rel=\"stylesheet\" \/&gt;\n&lt;\/head&gt;\n&lt;body&gt; &lt;div id=\"table-container\"&gt; &lt;table id=\"tab\"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th width=\"5%\"&gt;Id&lt;\/th&gt; &lt;th width=\"35%\"&gt;Name&lt;\/th&gt; &lt;th width=\"20%\"&gt;Price&lt;\/th&gt; &lt;th width=\"25%\"&gt;Category&lt;\/th&gt; &lt;th width=\"25%\"&gt;product Image&lt;\/th&gt; &lt;th width=\"20%\"&gt;Average Rating&lt;\/th&gt; &lt;\/tr&gt; &lt;\/thead&gt; &lt;tbody&gt; &lt;?php if (! empty($postResult)) { foreach ($postResult as $key =&gt; $value) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $postResult[$key][\"id\"]; ?&gt;&lt;\/td&gt; &lt;td&gt;&lt;?php echo $postResult[$key][\"name\"]; ?&gt;&lt;\/td&gt; &lt;td&gt;&lt;?php echo $postResult[$key][\"price\"]; ?&gt;&lt;\/td&gt; &lt;td&gt;&lt;?php echo $postResult[$key][\"category\"]; ?&gt;&lt;\/td&gt; &lt;td&gt;&lt;?php echo $postResult[$key][\"product_image\"]; ?&gt;&lt;\/td&gt; &lt;td&gt;&lt;?php echo $postResult[$key][\"average_rating\"]; ?&gt;&lt;\/td&gt; &lt;\/tr&gt; &lt;?php } } ?&gt; &lt;\/tbody&gt; &lt;\/table&gt; &lt;div class=\"btn\"&gt; &lt;form action=\"\" method=\"POST\"&gt; &lt;a href=\"&lt;?php echo strtok($_SERVER[\"REQUEST_URI\"]);?&gt;&lt;?php echo $_SERVER[\"QUERY_STRING\"];?&gt;?action=export\"&gt;&lt;button type=\"button\" id=\"btnExport\" name=\"Export\" value=\"Export to Excel\" class=\"btn btn-info\"&gt;Export to Excel&lt;\/button&gt;&lt;\/a&gt; &lt;\/form&gt; &lt;\/div&gt; &lt;\/div&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n<h3>PHP model calls prepare queries to fetch data to export<\/h3>\n<p>This is a PHP model class that is called to read data from the database. The data array will be sent to the export service to build the excel sheet object.<\/p>\n<p>The&nbsp;<em>getColumnName()<\/em> reads the database table column name array. This array will supply data to form the first row in excel to create a column header.<\/p>\n<p>The&nbsp;<em>getAllPost()<\/em> reads the data rows that will be iterated and set the data cells with the values.<\/p>\n<p class=\"code-heading\">lib\/Post.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php\nclass Post\n{ private $ds; public function __construct() { require_once __DIR__ . '\/DataSource.php'; $this-&gt;ds = new DataSource(); } public function getAllPost() { $query = \"select * from tbl_products\"; $result = $this-&gt;ds-&gt;select($query); return $result; } public function getColumnName() { $query = \"select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=N'tbl_products'\"; $result = $this-&gt;ds-&gt;select($query); return $result; }\n}\n?&gt;\n<\/code><\/pre>\n<h3>PHP excel export service<\/h3>\n<p>This service helps to export data to the excel sheet. The resultant file will be downloaded to the browser by setting the <a href=\"https:\/\/phppot.com\/php\/php-header\/\">PHP header() properties<\/a>.<\/p>\n<p>The $postResult has the row data and the $columnResult has the column data.<\/p>\n<p>This example instantiates the PHPSpreadSheet library class and sets the column header and values. Then it creates a writer object by setting the spreadsheet instance to output the data to excel.<\/p>\n<p class=\"code-heading\">lib\/ExportService.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php\nuse PhpOffice\\PhpSpreadsheet\\IOFactory;\nuse PhpOffice\\PhpSpreadsheet\\Spreadsheet;\nuse PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx;\nuse PhpOffice\\PhpSpreadsheet\\Calculation\\TextData\\Replace;\nrequire_once __DIR__ . '\/..\/vendor\/autoload.php'; class ExportService\n{ public function exportExcel($postResult, $columnResult) { $spreadsheet = new Spreadsheet(); $spreadsheet-&gt;getProperties()-&gt;setTitle(\"excelsheet\"); $spreadsheet-&gt;setActiveSheetIndex(0); $spreadsheet-&gt;getActiveSheet()-&gt;SetCellValue('A1', ucwords($columnResult[0][\"COLUMN_NAME\"])); $spreadsheet-&gt;getActiveSheet()-&gt;SetCellValue('B1', ucwords($columnResult[1][\"COLUMN_NAME\"])); $spreadsheet-&gt;getActiveSheet()-&gt;SetCellValue('C1', ucwords($columnResult[2][\"COLUMN_NAME\"])); $spreadsheet-&gt;getActiveSheet()-&gt;SetCellValue('D1', ucwords($columnResult[3][\"COLUMN_NAME\"])); $spreadsheet-&gt;getActiveSheet()-&gt;SetCellValue('E1', str_replace('_', ' ', ucwords($columnResult[4][\"COLUMN_NAME\"], '_'))); $spreadsheet-&gt;getActiveSheet()-&gt;SetCellValue('F1', str_replace('_', ' ', ucwords($columnResult[5][\"COLUMN_NAME\"], '_'))); $spreadsheet-&gt;getActiveSheet() -&gt;getStyle(\"A1:F1\") -&gt;getFont() -&gt;setBold(true); $rowCount = 2; if (! empty($postResult)) { foreach ($postResult as $k =&gt; $v) { $spreadsheet-&gt;getActiveSheet()-&gt;setCellValue(\"A\" . $rowCount, $postResult[$k][\"id\"]); $spreadsheet-&gt;getActiveSheet()-&gt;setCellValue(\"B\" . $rowCount, $postResult[$k][\"name\"]); $spreadsheet-&gt;getActiveSheet()-&gt;setCellValue(\"C\" . $rowCount, $postResult[$k][\"price\"]); $spreadsheet-&gt;getActiveSheet()-&gt;setCellValue(\"D\" . $rowCount, $postResult[$k][\"category\"]); $spreadsheet-&gt;getActiveSheet()-&gt;setCellValue(\"E\" . $rowCount, $postResult[$k][\"product_image\"]); $spreadsheet-&gt;getActiveSheet()-&gt;setCellValue(\"F\" . $rowCount, $postResult[$k][\"average_rating\"]); $rowCount ++; } $spreadsheet-&gt;getActiveSheet() -&gt;getStyle('A:F') -&gt;getAlignment() -&gt;setWrapText(true); $spreadsheet-&gt;getActiveSheet() -&gt;getRowDimension($rowCount) -&gt;setRowHeight(- 1); } $writer = IOFactory::createWriter($spreadsheet, 'Xls'); header('Content-Type: text\/xls'); $fileName = 'exported_excel_' . time() . '.xls'; $headerContent = 'Content-Disposition: attachment;filename=\"' . $fileName . '\"'; header($headerContent); $writer-&gt;save('php:\/\/output'); }\n}\n?&gt;\n<\/code><\/pre>\n<p><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/php\/php-excel-export.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/php\/php-excel-export\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on September 23rd, 2022. Export data to an excel file is mainly used for taking a backup. When taking database backup, excel format is a convenient one to read and manage easily. For some applications exporting data is important to take a backup or an offline copy of the server database. [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":128320,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-128319","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128319","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=128319"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128319\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/128320"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=128319"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=128319"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=128319"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}