Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created May 30, 2023 08:54
Show Gist options
  • Save code-boxx/28f257ad08511b30989baaa36bc7b476 to your computer and use it in GitHub Desktop.
Save code-boxx/28f257ad08511b30989baaa36bc7b476 to your computer and use it in GitHub Desktop.
PHP Export MYSQL Data To Excel

PHP EXPORT MYSQL DATA TO EXCEL

https://code-boxx.com/export-mysql-excel-spreadsheet-php/

NOTES

  1. A copy of PHPSpreadsheet is not included in, download by yourself – composer require phpoffice/phpspreadsheet.
  2. Create a dummy database and import 2-database.sql.
  3. Change the database settings in 3-db-spreadsheet.php to your own, and launch in the browser (or command line).

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1) Download and install Composer - https://getcomposer.org/
2) Open command line, navigate to project folder.
3) Run "composer require phpoffice/phpspreadsheet"
Done - Composer will download the latest version to the vendor/ folder.
PHPSpreadsheet - https://github.com/PHPOffice/PhpSpreadsheet
CREATE TABLE `users` (
`id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `email` (`email`),
ADD KEY `name` (`name`);
INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'John Doe', 'john@doe.com'),
(2, 'Jane Doe', 'jane@doe.com'),
(3, 'Apple Doe', 'apple@doe.com'),
(4, 'Beck Doe', 'beck@doe.com'),
(5, 'Charlie Doe', 'charlie@doe.com'),
(6, 'Charles Doe', 'charles@doe.com'),
(7, 'Dion Doe', 'dion@doe.com'),
(8, 'Dee Doe', 'dee@doe.com'),
(9, 'Emily Doe', 'emily@doe.com'),
(10, 'Ethan Doe', 'ethan@doe.com'),
(11, 'Frank Doe', 'frank@doe.com'),
(12, 'Gina Doe', 'gina@doe.com'),
(13, 'Hela Doe', 'hela@doe.com'),
(14, 'Hubert Doe', 'hubert@doe.com'),
(15, 'Ivy Doe', 'ivy@doe.com'),
(16, 'Ingrid Doe', 'ingrid@doe.com'),
(17, 'James Doe', 'james@doe.com'),
(18, 'Jace Doe', 'jace@doe.com'),
(19, 'Kate Doe', 'kate@doe.com'),
(20, 'Luke Doe', 'luke@doe.com');
<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN!
$dbhost = "localhost";
$dbname = "test";
$dbchar = "utf8mb4";
$dbuser = "root";
$dbpass = "";
$pdo = new PDO(
"mysql:host=$dbhost;charset=$dbchar;dbname=$dbname",
$dbuser, $dbpass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
]);
// (B) LOAD PHPSPREADSHEET
require "vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// (C) CREATE A NEW SPREADSHEET + WORKSHEET
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle("Users");
// (D) FETCH USERS + WRITE TO SPREADSHEET
$stmt = $pdo->prepare("SELECT * FROM `users`");
$stmt->execute();
$i = 1;
while ($row = $stmt->fetch()) {
$sheet->setCellValue("A".$i, $row["id"]);
$sheet->setCellValue("B".$i, $row["name"]);
$sheet->setCellValue("C".$i, $row["email"]);
$i++;
}
// (E) SAVE FILE
$writer = new Xlsx($spreadsheet);
$writer->save("users.xlsx");
echo "OK";
<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN!
$dbhost = "localhost";
$dbname = "test";
$dbchar = "utf8mb4";
$dbuser = "root";
$dbpass = "";
$pdo = new PDO(
"mysql:host=$dbhost;charset=$dbchar;dbname=$dbname",
$dbuser, $dbpass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
]);
// (B) CSV HTTP HEADERS
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=\"users.csv\"");
// (C) GET ENTRIES + OUTPUT
$stream = fopen("php://output", "w");
$stmt = $pdo->prepare("SELECT * FROM `users`");
$stmt->execute();
while ($row = $stmt->fetch()) { fputcsv($stream, $row); }
fclose($stream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment