Skip to main content

How to Convert SQL Database into Excel File (*.xlxs) in PHP


In this tutorial, we will convert sql to excel using PHP. This code will read all data from an SQL table then add it into an excel file using a class called "xlsxwriter.class.php". You can download the class using this link from Github

Things to do

You have to download and install XAMPP or any local server that run PHP scripts. In my case I used XAMPP as my local server, here's the download link for XAMPP server If you already installed a local server (XAMPP, WAMP, etc.), just ignore this step. I've included a SQL file in the downloadable of this tutorial. All you have to do is import the said file. If you have no idea on how to import, please visit nurhodelta_17's tutorial on How import .sql file to restore MySQL database. You should be able to create a database named guessmynumber.

Database Connection

  1. <?php $conn=mysqli_connect('localhost','root','','guessmynumber'); ?>

Include Main Class

  1. <?php include_once("xlsxwriter.class.php"); ?>

Create array from Query Result

  1. <?php
  2. $user_query = mysqli_query($conn,'select * from gmn_questions');
  3. $rows = array();
  5. //about this, read documentation of class from github
  6. $header = array(
  7. 'Question ID'=>'integer',
  8. 'Question Clue'=>'string',
  9. 'Question Answer'=>'integer',
  10. );
  12. while ($datafromsql = mysqli_fetch_assoc($user_query)) {
  13. $rows[] = $datafromsql;
  14. }
  16. //secret code here. To view code, click "Download Code" Button below.
  17. ?>

Download Excel File

  1. <?php
  2. $file = "output.xlsx" ;
  3. header('Content-Disposition: attachment; filename=' . $file );
  4. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  5. header('Content-Length: ' . filesize($file));
  6. header('Content-Transfer-Encoding: binary');
  7. header('Cache-Control: must-revalidate');
  8. header('Pragma: public');
  9. ?>
Tutorial done. I hope that this simple tutorial helps you. Enjoy Coding!!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.


1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.


Add new comment