Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] PHP Excel Export Code (Data to File)

#1
PHP Excel Export Code (Data to File)

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/09/php-excel-export-code-data-to-file.jpg" width="550" height="471" title="" alt="" /></div><div><div class="modified-on" readability="7.1666666666667"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on September 23rd, 2022.</div>
<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>
<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>
<p><strong>This article uses the PHPSpreadSheet library for implementing PHP excel export.</strong></p>
<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>
<p>The complete example in this article will let create your own export tool or your application.<br /><img 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/20...00x257.jpg 300w, https://phppot.com/wp-content/uploads/20...68x658.jpg 768w, https://phppot.com/wp-content/uploads/20...export.jpg 916w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>About this Example</h2>
<p>It will show a minimal interface with the list of database records and an “Export to Excel” button. By clicking this button, it will call the custom ExportService created for this example.</p>
<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>
<p>Follow the below steps to let this example run in your environment.</p>
<ol>
<li>Create and set up the database with data exported to excel.</li>
<li>Download the code at the end of this article and configure the database.</li>
<li>Add PHPSpreadSheet library and other dependencies into the application.</li>
</ol>
<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>
<h2>1) Create and set up the database with data exported to excel</h2>
<p>Create a database named “db_excel_export” and import the below SQL script into it.</p>
<p class="code-heading">structure.sql</p>
<pre class="prettyprint"><code class="language-sql">--
-- Table structure for table `tbl_products`
-- 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
); --
-- Dumping data for table `tbl_products`
-- INSERT INTO `tbl_products` (`id`, `name`, `price`, `category`, `product_image`, `average_rating`) VALUES
(1, 'Tiny Handbags', 100.00, 'Fashion', 'gallery/handbag.jpeg', 5.0),
(2, 'Men\'s Watch', 300.00, 'Generic', 'gallery/watch.jpeg', 4.0),
(3, 'Trendy Watch', 550.00, 'Generic', 'gallery/trendy-watch.jpeg', 4.0),
(4, 'Travel Bag', 820.00, 'Travel', 'gallery/travel-bag.jpeg', 5.0),
(5, 'Plastic Ducklings', 200.00, 'Toys', 'gallery/ducklings.jpeg', 4.0),
(6, 'Wooden Dolls', 290.00, 'Toys', 'gallery/wooden-dolls.jpeg', 5.0),
(7, 'Advanced Camera', 600.00, 'Gadget', 'gallery/camera.jpeg', 4.0),
(8, 'Jewel Box', 180.00, 'Fashion', 'gallery/jewel-box.jpeg', 5.0),
(9, 'Perl Jewellery', 940.00, 'Fashion', 'gallery/perls.jpeg', 5.0); --
-- Indexes for dumped tables
-- --
-- Indexes for table `tbl_products`
--
ALTER TABLE `tbl_products` ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `tbl_products`
--
ALTER TABLE `tbl_products` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
</code></pre>
<h2>2) Download the code and configure the database</h2>
<p>The source code contains the following files. This section explains the database configuration.</p>
<p><img 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>
<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>
<pre class="prettyprint"><code class="language-php">&lt;?php class DataSource
{ const HOST = 'localhost'; const USERNAME = 'root'; const PASSWORD = ''; const DATABASENAME = 'db_excel_export'; ... ...
?&gt;
</code></pre>
<h2>3) Add PHPSpreadSheet library and other dependencies into the application</h2>
<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>
<p>It gives the composer command to add the PHPSpreadsheet and related dependencies into the application.</p>
<pre class="prettyprint"><code>composer require phpoffice/phpspreadsheet
</code></pre>
<h3>For PHP version 7</h3>
<p>Add the below specification to the composer.json file.</p>
<pre class="prettyprint"><code>{ "require": { "phpoffice/phpspreadsheet": "^1.23" }, "config": { "platform": { "php": "7.3" } }
}
</code></pre>
<p>then run</p>
<pre class="prettyprint"><code>composer update
</code></pre>
<p><strong>Note:</strong> PHPSpreadsheet requires at least PHP 7.3 version.</p>
<h2>How it works</h2>
<h3>Simple interface with export option</h3>
<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 “Excel Export” button.</p>
<p>By clicking this button the action parameter is sent to the URL to call the excel export service in PHP.</p>
<p class="code-heading">index.php</p>
<pre class="prettyprint"><code class="language-php-template">&lt;?php
require_once __DIR__ . '/lib/Post.php';
$post = new post();
$postResult = $post-&gt;getAllPost();
$columnResult = $post-&gt;getColumnName();
if (! empty($_GET["action"])) { require_once __DIR__ . '/lib/ExportService.php'; $exportService = new ExportService(); $result = $exportService-&gt;exportExcel($postResult, $columnResult);
}
?&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
&lt;link href="./style.css" type="text/css" rel="stylesheet" /&gt;
&lt;/head&gt;
&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;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3>PHP model calls prepare queries to fetch data to export</h3>
<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>
<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>
<p>The&nbsp;<em>getAllPost()</em> reads the data rows that will be iterated and set the data cells with the values.</p>
<p class="code-heading">lib/Post.php</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
class Post
{ 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; }
}
?&gt;
</code></pre>
<h3>PHP excel export service</h3>
<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>
<p>The $postResult has the row data and the $columnResult has the column data.</p>
<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>
<p class="code-heading">lib/ExportService.php</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace;
require_once __DIR__ . '/../vendor/autoload.php'; class ExportService
{ 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'); }
}
?&gt;
</code></pre>
<p><a class="download" href="https://phppot.com/downloads/php/php-excel-export.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-excel-export/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/09/...a-to-file/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016