Tuesday 25 September 2018

Read excel file and import data into MySQL database using PHPExcel

Sometimes, we need to read a huge amount of data from excel files (.xls or .xlsx in extension) and have to store these data into a database for future use. We can achieve this by using PHP, PHPExcel library, and MySQL. this So, in this tutorial, I will explain to you how to read excel file and import data into MySQL database using PHPExcelPHPExcel is a PHP library for reading and writing spreadsheet files. In this tutorial, we will use MySQL database for storing data extracted from excel file.
Also, you can enjoy the live demo example of read excel file and import data into MySQL database using PHPExcel for better understanding. As well as you can get the full source code from the download link.

MySQL Database Table

  1. CREATE TABLE IF NOT EXISTS `user_details` (
  2. `id` int(11) NOT NULL,
  3. `name` varchar(50) NOT NULL,
  4. `mobile` bigint(10) NOT NULL,
  5. `country` varchar(50) NOT NULL
  6. );
If you want to store or import excel data into MySQL database, you need a database table. So, create the user_details table in the database. Copy the above query and execute in your database query editor.

Database Configuration (db.php)

  1. <?php
  2. define('HOSTNAME','localhost');
  3. define('DB_USERNAME','username');
  4. define('DB_PASSWORD','password');
  5. define('DB_NAME', 'database-name');
  6. //global $con;
  7. $con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
  8. // Check connection
  9. if(mysqli_connect_errno($con)) echo "Failed to connect MySQL: " .mysqli_connect_error();
  10. ?>
The above PHP code will establish the connection with your MySQL database. Just replace the username, password, and database-name with your credentials.

Upload Form (index.php)

  1. <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
  2. Upload excel file :
  3. <input type="file" name="uploadFile" value="" />
  4. <input type="submit" name="submit" value="Upload" />
  5. </form>
A simple HTML form for uploading excel file into the server. Excel file with both .xls and .xlsx extensions are applicable in this example.

Read excel file and import into MySQL table (index.php)

  1. <?php
  2. if(isset($_POST['submit'])) {
  3. if(isset($_FILES['uploadFile']['name']) && $_FILES['uploadFile']['name'] != "") {
  4. $allowedExtensions = array("xls","xlsx");
  5. $ext = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
  6. if(in_array($ext, $allowedExtensions)) {
  7. $file_size = $_FILES['uploadFile']['size'] / 1024;
  8. if($file_size < 50) {
  9. $file = "uploads/".$_FILES['uploadFile']['name'];
  10. $isUploaded = copy($_FILES['uploadFile']['tmp_name'], $file);
  11. if($isUploaded) {
  12. include("db.php");
  13. include("Classes/PHPExcel/IOFactory.php");
  14. try {
  15. //Load the excel(.xls/.xlsx) file
  16. $objPHPExcel = PHPExcel_IOFactory::load($file);
  17. } catch (Exception $e) {
  18. die('Error loading file "' . pathinfo($file, PATHINFO_BASENAME). '": ' . $e->getMessage());
  19. }
  20. //An excel file may contains many sheets, so you have to specify which one you need to read or work with.
  21. $sheet = $objPHPExcel->getSheet(0);
  22. //It returns the highest number of rows
  23. $total_rows = $sheet->getHighestRow();
  24. //It returns the highest number of columns
  25. $total_columns = $sheet->getHighestColumn();
  26. echo '<h4>Data from excel file</h4>';
  27. echo '<table cellpadding="5" cellspacing="1" border="1" class="responsive">';
  28. $query = "insert into `user_details` (`id`, `name`, `mobile`, `country`) VALUES ";
  29. //Loop through each row of the worksheet
  30. for($row =2; $row <= $total_rows; $row++) {
  31. //Read a single row of data and store it as a array.
  32. //This line of code selects range of the cells like A1:D1
  33. $single_row = $sheet->rangeToArray('A' . $row . ':' . $total_columns . $row, NULL, TRUE, FALSE);
  34. echo "<tr>";
  35. //Creating a dynamic query based on the rows from the excel file
  36. $query .= "(";
  37. //Print each cell of the current row
  38. foreach($single_row[0] as $key=>$value) {
  39. echo "<td>".$value."</td>";
  40. $query .= "'".mysqli_real_escape_string($con, $value)."',";
  41. }
  42. $query = substr($query, 0, -1);
  43. $query .= "),";
  44. echo "</tr>";
  45. }
  46. $query = substr($query, 0, -1);
  47. echo '</table>';
  48. // At last we will execute the dynamically created query an save it into the database
  49. //mysqli_query($con, $query);
  50. if(mysqli_affected_rows($con) > 0) {
  51. echo '<span class="msg">Database table updated!</span>';
  52. } else {
  53. echo '<span class="msg">Can\'t update database table! try again.</span>';
  54. }
  55. // Finally we will remove the file from the uploads folder (optional)
  56. unlink($file);
  57. } else {
  58. echo '<span class="msg">File not uploaded!</span>';
  59. }
  60. } else {
  61. echo '<span class="msg">Maximum file size should not cross 50 KB on size!</span>';
  62. }
  63. } else {
  64. echo '<span class="msg">This type of file not allowed!</span>';
  65. }
  66. } else {
  67. echo '<span class="msg">Select an excel file first!</span>';
  68. }
  69. }
  70. ?>

Example Explained

First, we will go through the validation process. We will check whether the file is uploaded or not, if uploaded then we will check the file extension, and also we will check the file size. Here in this example, the maximum file size is limited to 50 KB in size.
pathinfo($_FILES[‘uploadFile’][‘name’], PATHINFO_EXTENSION) – Returns the extension of the file.
$objPHPExcel->getSheet(0) – An excel file may contain many sheets, so you have to specify which one you need to read or work with.
$sheet->getHighestRow() – Returns the highest number of rows.
$sheet->getHighestColumn() – Returns the highest number of columns.
$sheet->rangeToArray(‘A’ . $row . ‘:’ . $highest_column . $row, NULL, TRUE, FALSE) – Read a single row of data and store it as an array.
unlink($file) – Removes the file from the specified path.

Complete source code – Read excel file and import data into MySQL database using PHPExcel

Try the live demo example of Read excel file and import data into MySQL database using PHPExcel. Download the complete source code from the below download link and please like and share the tutorial link with others.


0 comments:

Post a Comment