Hello everyone. Today in this article, I will explain to you about exporting the reports in Excel format using PHP and MySQL. So, I will create one simple PHP page that will display data from the My SQL database in tabular format and then we put one button. By clicking this button, we can export the Excel file which is automatically downloaded to your machine.
- Make Table in My SQL for storing the user. Give it the name “tbl_User”. This table contains UserName, Password etc. For creating a table, run the below script.
- CREATE TABLE IF NOT EXISTS `tbl_user` (
- `ur_Id` int(11) NOT NULL AUTO_INCREMENT,
- `ur_username` varchar(50) NOT NULL,
- `ur_password` varchar(50) NOT NULL,
- `ur_status` int(11) NOT NULL,
- PRIMARY KEY (`ur_Id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
By running the above script, it will create a table like below. Here, table contains Id, Username, Password, Status etc… columns
- Now, insert some temporary data to this table. So, for inserting data in the temporary table, I run the below SQL script.
- INSERT INTO `tbl_user` (`ur_Id`, `ur_username`, `ur_password`, `ur_status`) VALUES
- (1, '[email protected]', 'nirav', 1),
- (2, '[email protected]', 'kapil', 1),
- (3, '[email protected]', 'arvind', 1);
After running the below script you can show a table something like below.
- Now, first we make one simple PHP page that will display the above table data in tabular format with one “Export link”.
- <html>
-
- <head>
- <title>User Detail Report</title>
- </head>
-
- <body> </body>
-
- </html>
Save the above file with “UserReport.php”.
2. Now, we will add one table for displaying the data. Our table contains 3 columns, “Sr No”, “User Name” ,” Password”.
- <table border="1">
- <tr>
- <th>Sr NO.</th>
- <th width="120">User Name</th>
- <th>Password</th>
- </tr>
- </table>
Here, we take table border as “1” so user can display, and we create 3 columns for the table header rows.
- Now, we have to fetch the SQL table value for displaying table data rows. So, first we make MySQL Server database connection. Now, we make MySQL server connection from the PHP file. So, pass server name, user name, password, database name etc.
- <?php
- $conn = new mysqli('localhost', 'root', '');
- mysqli_select_db($conn, 'EmployeeDB');
- ?>
Here, we pass server name as ‘localhost’, username as ‘root’, password to be blank(’’), and we pass database name as ‘EmployeeDB’.
- Now, we make Query which will select the SrNo, Username and password from the database and pass this with MySQL connection object. As show below:
- $sql = mysqli_query($conn,"SELECT `ur_Id`,`ur_username`,`ur_password` FROM `tbl_user`");
Above, Query fetches the records from the MySQL database and stores it in “$sql” variable.
- Here, we have record set. So, now we separate it in row-wise data. Repeat the while loop and fetch each row and show in tabular format, as show below:
- while($data = mysqli_fetch_row($sql))
- {
- echo '
- <tr>
- <td>'.$data[0].'</td>
- <td>'.$data[1].'</td>
- <td>'.$data[2].'</td>
- </tr>
- ';
- }
Above code will display the data row for the table. So, now complete table with header row and data row is displayed.
- Now, we put one link; that is, export the data to Excel file.
- <a href="UserReport_Export.php"> Export To Excel </a>
- Now, complete code for the “UserReport.php” is shown below:
- <html>
-
- <head>
- <title>User Detail Report</title>
- </head>
-
- <body>
- <table border="1">
- <tr>
- <th>Sr NO.</th>
- <th width="120">User Name</th>
- <th>Password</th>
- </tr>
- <?php
- $conn = new mysqli('localhost', 'root', '');
- mysqli_select_db($conn, 'EmployeeDB');
-
- $sql = mysqli_query($conn,"SELECT `ur_Id`,`ur_username`,`ur_password` FROM `tbl_user`");
-
-
- while($data = mysqli_fetch_row($sql)){
- echo '
- <tr>
- <td>'.$data[0].'</td>
- <td>'.$data[1].'</td>
- <td>'.$data[2].'</td>
- </tr>
- ';
- }
- ?>
- </table> <a href="UserReport_Export.php"> Export To Excel </a> </body>
-
- </html>
Run the above PHP page http://localhost:8081/UserReport.php, It displays like this,
Here, displaying the table data in PHP page is now complete. Now, we have to create file for exporting this table data to excel file in PHP.
- Create another PHP file for exporting data to excel and give its name “UserReport_Export.php”. And, write the below code :
- First, I create the My SQL connection for fetching the data from the database, as shown in above steps.
- $conn = new mysqli('localhost', 'root', '');
- mysqli_select_db($conn, 'EmployeeDB');
-
- $setSql = "SELECT `ur_Id`,`ur_username`,`ur_password` FROM `tbl_user`";
- $setRec = mysqli_query($conn,$setSql);
Here, in variable $setRec, record set is stored. So, we loop the record set and separate the each row of record by writing while loop to fetch each row.
- while($rec = mysqli_fetch_row($setRec))
- {
- }
- Now, we have to get the column wise data from the row. So, we write “for each” loop in while loop.
- foreach($rec as $value)
- {
- }
- Now, we have to add one tab (“\t”) value between each and every column values and store this full string to any new variable. So, we write some function in between for each loop, as show below,
- $rowData = '';
- foreach($rec as $value)
- {
- $value = '"' . $value . '"' . "\t";
- $rowData .= $value;
- }
- Now, our columns are ready. We have to separate the rows now. So, we have to add new line character (“\n”) between each new row:
- $setData='';
-
- while($rec = mysqli_fetch_row($setRec))
- {
- $rowData = '';
- foreach($rec as $value)
- {
- $value = '"' . $value . '"' . "\t";
- $rowData .= $value;
- }
- $setData .= trim($rowData)."\n";
- }
- Our table data row and columns are ready now. We have to define a new variable for header row, as shown in below code,
- $columnHeader ='';
- $columnHeader = "Sr NO"."\t"."User Name"."\t"."Password"."\t";
- Here, when user clicks on link, we have to download the excel file directly, without showing the data. Just add the below code.
header("Content-type: application/octet-stream");
- Now, we have to set the filename for downloading excel file.
header("Content-Disposition: attachment; filename=User_Detail_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
- Now, finally we print all the table row data and header data to the excel file.
echo ucwords($columnHeader)."\n".$setData."\n";
Complete code for “UserReport_Export.php”,
- <?php
-
- $conn = new mysqli('localhost', 'root', '');
- mysqli_select_db($conn, 'EmployeeDB');
-
- $setSql = "SELECT `ur_Id`,`ur_username`,`ur_password` FROM `tbl_user`";
- $setRec = mysqli_query($conn, $setSql);
-
- $columnHeader = '';
- $columnHeader = "Sr NO" . "\t" . "User Name" . "\t" . "Password" . "\t";
-
- $setData = '';
-
- while ($rec = mysqli_fetch_row($setRec)) {
- $rowData = '';
- foreach ($rec as $value) {
- $value = '"' . $value . '"' . "\t";
- $rowData .= $value;
- }
- $setData .= trim($rowData) . "\n";
- }
-
-
- header("Content-type: application/octet-stream");
- header("Content-Disposition: attachment; filename=User_Detail_Reoprt.xls");
- header("Pragma: no-cache");
- header("Expires: 0");
-
- echo ucwords($columnHeader) . "\n" . $setData . "\n";
-
- ?>
- Now, run the “UserReport.php” in your WAMP or any other related server. It will show like the below image and then, click on “Export to Excel” link . It will download the excel file, as show in below.
- Now, open the Excel file and show the result.
Thank you for reading my article , if you have any problem than fill free to ask in comment box.