How to create a simple Microsoft Excel spreadsheet with PHP only
I’ve had the need to create many spreadsheet exports over the years for various clients and found the simplest way to do it without having to install specific libraries or third party software is to just create the spreadsheet with plain PHP.
The following script will create a comma delimited excel spreadsheet named spreadsheet_name.xls. When you browse to the page with this script the page will produce the export and provide a link to open it.
How to create a simple excel spreadsheet using PHP.
<?php // prep the download $fileName = "../downloads/spreadsheet_name.xls"; if (file_exists($fileName)) { @unlink($fileName); } $file = @fopen($fileName, "wb") or die("ERROR: Unable to access file system - Process aborted."); $header = array("Last Name", "First Name", "Application Date"); fputcsv($file, $header, ",", '"'); // get records $query = "SELECT lname, fname, application_date"; $query .= " FROM applications"; $result = querySelect($query); // external function to query the database if (count($result) > 0) { foreach($result as $row) { $fname = $row["fname"]; $lname = $row["lname"]; $application_date = $row["application_date"]; $fields = array($lname, $fname, $application_date); fputcsv($file, $fields, ",", '"'); } } fclose($file); echo "<a href='$fileName'>$fileName</a>"; ?>
References
PHP file_exists
PHP unlink
PHP fopen
PHP die
PHP arrays
PHP fputcsv
PHP fclose
PHP echo