Tuesday, 25 September 2018

Write data in excel file from database using PHP

In this article, I will show you how to use PHPExcel library to write data in excel file. The data which will be written in the excel file will be fetched from the database. In this tutorial we will use MySQL database, you can choose another database if you want. You can also check my previous tutorial which lets you help to Read excel file and import data into MySQL database using PHP.

PHP code – Write data in excel file

  1. //Include PHPExcel
  2. require_once("Classes/PHPExcel.php");
  3. //Create a PHPExcel object
  4. $objPHPExcel = new PHPExcel();
Before starting anything you should include the PHPExcel.php page into your web application. Then create a new object of PHPExcel class.
  1. //Set document properties
  2. $objPHPExcel->getProperties()->setCreator("Mitrajit Samanta")
  3. ->setLastModifiedBy("Mitrajit Samanta")
  4. ->setTitle("User's Information")
  5. ->setSubject("User's Personal Data")
  6. ->setDescription("Description of User's")
  7. ->setKeywords("")
  8. ->setCategory("");
  9. //Set default font style and size
  10. $objPHPExcel->getDefaultStyle()->getFont()->setName('Arial')
  11. ->setSize(10);
  12. //Set the first row as the header row
  13. $objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID')
  14. ->setCellValue('B1', 'NAME')
  15. ->setCellValue('C1', 'MOBILE')
  16. ->setCellValue('D1', 'COUNTRY');
  17. //Rename the worksheet
  18. $objPHPExcel->getActiveSheet()->setTitle('USER INFO');
  19. //Set active worksheet index to the first sheet, so Excel opens this as the first sheet
  20. $objPHPExcel->setActiveSheetIndex(0);
You can set different types of properties to the excel file such as creator’s name, who last modified, title, subject and much more. Also, you can manage the font family and size of the excel file. In the last line, the cells from A1 to D1 of the first row is set as the header row. setTitle(…) function rename the worksheet name. setActiveSheetIndex(0) function set the first worksheet as active sheet. Excel will open this as the first sheet.

Fetching data from database – Write data in excel file

  1. $sql = "select * from `user_details`";
  2. $res = mysqli_query($con, $sql);
  3. if(mysqli_num_rows($res)>0)
  4. {
  5. $i = 2;
  6. while($row = mysqli_fetch_object($res)) {
  7. $objPHPExcel->getActiveSheet()->setCellValue('A'.($i), $row->id)
  8. ->setCellValue('B'.($i), $row->name)
  9. ->setCellValue('C'.($i), $row->mobile)
  10. ->setCellValue('D'.($i), $row->country);
  11. $i++;
  12. }
  13. }
The above simple query returns all rows from the table. The initial value of the variable $i is 2. Because the first row of the excel is already occupied as the header row. So, we will start inserting the data from the second row. The cell range will be A2:D2. Next A3:D3. We will set the value of each cell by calling the function setCellValue(“cell number”,”value”).

Generate the excel file

  1. //Dynamic name, the combination of date and time
  2. $filename = date('d-m-Y_H-i-s').".xlsx";
  3. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  4. //if you want to save the file on the server instead of downloading,
  5. //comment the last 3 lines and remove the comment from the next line
  6. //$objWriter->save(str_replace('.php', '.xlsx', $filename));
  7. header('Content-type: application/vnd.ms-excel');
  8. header('Content-Disposition: attachment; filename='.$filename);
  9. $objWriter->save("php://output");
The file name of the excel is dynamic, the combination of date and time. At last, we forced to download the file as an excel in the browser. If you want to save file on the server instead of downloading comment the last three lines and remove the comment from the line //$objWriter->save(str_replace(‘.php’, ‘.xlsx’, $filename));.

Database – Write data into CSV file

  1. CREATE TABLE IF NOT EXISTS `user_details` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(50) NOT NULL,
  4. `mobile` bigint(10) NOT NULL,
  5. `country` varchar(50) NOT NULL,
  6. PRIMARY KEY (`id`)
  7. );
  8. INSERT INTO `user_details` (`id`, `name`, `mobile`, `country`) VALUES
  9. (1, 'Aritra Samanta', 9999999991, 'India'),
  10. (2, 'Rina Saha', 9999999992, 'Australia'),
  11. (3, 'Anil Das', 9999999993, 'London'),
  12. (4, 'Akash Samanta', 9999999994, 'America'),
  13. (5, 'Niharika Roy', 9999999995, 'Bulgeria');
Create the above table into the database and insert the dummy data into that table.
  1. <?php
  2. define('HOSTNAME','localhost');
  3. define('DB_USERNAME','database_username');
  4. define('DB_PASSWORD','database_password');
  5. define('DB_NAME', 'database_name');
  6. $con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
  7. //Check connection
  8. if(mysqli_connect_errno($con)) echo "Failed to connect MySQL: " .mysqli_connect_error();
  9. ?>
Create a PHP file “db.php” in the root folder and write the above database connection code into it. Change the database credentials according to yours.

Download the complete source code

index.php
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  5. <title>Write data in excel file from database using PHP || Mitrajit's Tech Blog</title>
  6. <style>
  7. body { font-family:Arial, Helvetica, sans-serif; font-size:14px; }
  8. h1 { clear:both; margin-bottom:30px; font-size:17px; }
  9. h1 a { font-weight:bold; color:#0099FF; }
  10. span { clear:both; display:block; margin-bottom:30px; }
  11. span a { font-weight:bold; color:#0099FF; }
  12. #submitBtn {
  13. padding:5px 15px;
  14. background-color:#0099FF;
  15. border-radius:5px;
  16. margin-bottom:5px;
  17. border:2px solid #ccc;
  18. color:#fff;
  19. cursor:pointer;
  20. font-weight:bold;
  21. }
  22. #submitBtn:hover {
  23. background-color:#00CCFF;
  24. }
  25. table { border:1px solid #ccc; width:600px; color:#fff; }
  26. table th {
  27. background-color:#0099FF;
  28. color:#fff;
  29. }
  30. td {
  31. background-color:#00CCFF;
  32. height:40px;
  33. text-align:center;
  34. }
  35. .div_ok, .div_fail {
  36. width:590px;
  37. background-color:#3399FF;
  38. padding:5px;
  39. margin-top:10px;
  40. color:#fff;
  41. }
  42. .div_fail {
  43. background-color:#FF0000;
  44. }
  45. </style>
  46. </head>
  47. <body>
  48. <h1>Read the full article -- <a href="http://www.mitrajit.com/2016/12/write-data-excel-file-database-using-php/" target="_blank">Write data in excel file from database using PHP</a> -- in <a href="http://www.mitrajit.com">Mitrajit's Tech Blog</a></h1>
  49. <?php
  50. include("db.php");
  51. $sql = "select * from `user_details`";
  52. $res = mysqli_query($con, $sql);
  53. if(mysqli_num_rows($res) > 0) {
  54. ?>
  55. <form action="excel.php" method="post">
  56. <input type="submit" name="submitBtn" id="submitBtn" value="Generate Excel" />
  57. <table cellpadding="5" cellspacing="1">
  58. <tbody>
  59. <tr>
  60. <th>SL.</th>
  61. <th>NAME</th>
  62. <th>MOBILE</th>
  63. <th>COUNTRY</th>
  64. </tr>
  65. <?php
  66. while($row = mysqli_fetch_array($res)) {
  67. ?>
  68. <tr>
  69. <td align="center"><?php echo $row['id']; ?>.</td>
  70. <td><?php echo $row['name']; ?></td>
  71. <td align="center"><?php echo $row['mobile']; ?></td>
  72. <td><?php echo $row['country']; ?></td>
  73. </tr>
  74. <?php
  75. }
  76. ?>
  77. </tbody>
  78. </table>
  79. </form>
  80. <?php
  81. }
  82. ?>
  83. </body>
  84. </html>
excel.php
  1. <?php
  2. include('db.php');
  3. //Include PHPExcel.php
  4. require_once("Classes/PHPExcel.php");
  5. //Create a PHPExcel object
  6. $objPHPExcel = new PHPExcel();
  7. //Set document properties
  8. $objPHPExcel->getProperties()->setCreator("Mitrajit Samanta")
  9. ->setLastModifiedBy("Mitrajit Samanta")
  10. ->setTitle("User's Information")
  11. ->setSubject("User's Personal Data")
  12. ->setDescription("Description of User's")
  13. ->setKeywords("")
  14. ->setCategory("");
  15. // Set default font
  16. $objPHPExcel->getDefaultStyle()->getFont()->setName('Arial')
  17. ->setSize(10);
  18. //Set the first row as the header row
  19. $objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID')
  20. ->setCellValue('B1', 'NAME')
  21. ->setCellValue('C1', 'MOBILE')
  22. ->setCellValue('D1', 'COUNTRY');
  23. //Rename the worksheet
  24. $objPHPExcel->getActiveSheet()->setTitle('USER INFO');
  25. //Set active worksheet index to the first sheet, so Excel opens this as the first sheet
  26. $objPHPExcel->setActiveSheetIndex(0);
  27. /*************** Fetching data from database ***************/
  28. $sql = "select * from `user_details`";
  29. $res = mysqli_query($con, $sql);
  30. if(mysqli_num_rows($res)>0)
  31. {
  32. $i = 2;
  33. while($row = mysqli_fetch_object($res)) {
  34. $objPHPExcel->getActiveSheet()->setCellValue('A'.($i), $row->id)
  35. ->setCellValue('B'.($i), $row->name)
  36. ->setCellValue('C'.($i), $row->mobile)
  37. ->setCellValue('D'.($i), $row->country);
  38. $i++;
  39. }
  40. }
  41. //Dynamic name, the combination of date and time
  42. $filename = date('d-m-Y_H-i-s').".xlsx";
  43. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  44. //if you want to save the file on the server instead of downloading,
  45. //comment the last 3 lines and remove the comment from the next line
  46. //$objWriter->save(str_replace('.php', '.xlsx', $filename));
  47. header('Content-type: application/vnd.ms-excel');
  48. header('Content-Disposition: attachment; filename='.$filename);
  49. $objWriter->save("php://output");
Download the full source code from the download link below and please like and share the tutorial link to others.

0 comments:

Post a Comment