etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

PHP import Excel data to MySQL using PHPExcel

In this article, you will learn how to import Excel data into the MySQL database using the PHPExcel library. PHPExcel is a library written in pure PHP and provides a set of classes that allow you to write to and read from different spreadsheet file formats.





The web applications may contain data in various formats or they may have to collect data from various sources. It is not necessary that all the gathered data be compatible for storage on the server. Most large-scale websites use server-side code to dynamically display different data when needed. A database stores information more efficiently and can handle volumes of information that would be unmanageable in a spreadsheet. Spreadsheets have record limitations, whereas a database does not. So, we need to store this data in a database for future use. Here, we are using the PHPExcel library to import a CSV file into a PHP database. You can easily implement this by following these steps.





These are the steps to import Excel data to MySQL using PHPExcel-


Install PHPExcel with Composer

First, we need to install the PHPExcel library to read excel data. You can either download this from Github or install it using Composer. If your system does not have composer installed, then first download the latest composer version from its official website-

https://getcomposer.org/download/

You can check a successful installation using the following command on cmd-

Install Composer

Now, go to your project directory on the command prompt and run the following command to install the PHPExcel library.

E:\wamp\www\exceltomysql>composer require phpoffice/phpexcel

After this, you will notice that Composer has downloaded all libraries under the 'vendor' directory of your project root. Here is the file structure of this project-

PHPExcel file Structure



Excel File

Suppose we have the following excel file containing school program participants data-

PHPExcel file Structure

Database Script (db.php)

Here, we have written the database connection code. Make sure to replace 'hostname', 'username', 'password' and 'database' with your database credentials and name.

<?php
	$hostname = "localhost";
	$db = "school";
	$password = "";
	$user = "root";
	$mysqli = new mysqli($hostname, $user, $password, $db);
?>

If we want to store or import Excel data into the MySQL database, we need a database table. So, we have a MySQL database 'school' and in it we have to create a 'participants' table with the given columns.

CREATE TABLE IF NOT EXISTS `participants` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `rollno` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `program` varchar(100) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;




Create Upload File Template

To create a file uploader, we have created a simple HTML file upload form 'index.php'. If a form contains any file type input field, then we have to add an attribute 'encrypt' with a value of 'multipart/form-data'.

<!DOCTYPE html>
<html>
<head>
	<title>PHP import Excel data</title>
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<h1>Upload Excel File</h1>
	<form method="POST" action="uploadexcel.php" enctype="multipart/form-data">
		<div class="form-group">
			<label>Choose File</label>
			<input type="file" name="uploadFile" class="form-control" />
		</div>
		<div class="form-group">
			<button type="submit" name="submit" class="btn btn-success">Upload</button>
		</div>
	</form>
</div>
</body>
</html>




Parse Excel and Insert into Database (uploadexcel.php)

In this PHP code, we have validated the uploaded file type and then included the PHPExcel library files and database configuration file (db.php). We have validated the execution of each logical code. It returns an error message on failure. Further, PHPExcel parses the excel file, reads the data, and stores it in an array. We have looped over this array to insert data into the database and show the response to the web browser.

<?php  

if(isset($_POST['submit'])) {
     if(isset($_FILES['uploadFile']['name']) && $_FILES['uploadFile']['name'] != "") {
        $allowedExtensions = array("xls","xlsx");
        $ext = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
		
        if(in_array($ext, $allowedExtensions)) {
				// Uploaded file
               $file = "uploads/".$_FILES['uploadFile']['name'];
               $isUploaded = copy($_FILES['uploadFile']['tmp_name'], $file);
			   // check uploaded file
               if($isUploaded) {
					// Include PHPExcel files and database configuration file
                    include("db.php");
					require_once __DIR__ . '/vendor/autoload.php';
                    include(__DIR__ .'/vendor/phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php');
                    try {
                        // load uploaded file
                        $objPHPExcel = PHPExcel_IOFactory::load($file);
                    } catch (Exception $e) {
                         die('Error loading file "' . pathinfo($file, PATHINFO_BASENAME). '": ' . $e->getMessage());
                    }
                    
                    // Specify the excel sheet index
                    $sheet = $objPHPExcel->getSheet(0);
                    $total_rows = $sheet->getHighestRow();
					$highestColumn      = $sheet->getHighestColumn();	
					$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);		
					
					//	loop over the rows
					for ($row = 1; $row <= $total_rows; ++ $row) {
						for ($col = 0; $col < $highestColumnIndex; ++ $col) {
							$cell = $sheet->getCellByColumnAndRow($col, $row);
							$val = $cell->getValue();
							$records[$row][$col] = $val;
						}
					}
					$html="<table border='1'>";
					$html.="<tr><th>Roll No</th>";
					$html.="<th>Name</th><th>Age</th>";
					$html.="<th>Program</th></tr>";
					foreach($records as $row){
						// HTML content to render on webpage
						$html.="<tr>";
						$rollno = isset($row[0]) ? $row[0] : '';
						$name = isset($row[1]) ? $row[1] : '';
						$age = isset($row[2]) ? $row[2] : '';
						$program = isset($row[3]) ? $row[3] : '';
						$html.="<td>".$rollno."</td>";
						$html.="<td>".$name."</td>";
						$html.="<td>".$age."</td>";
						$html.="<td>".$program."</td>";
						$html.="</tr>";
						// Insert into database
						$query = "INSERT INTO participants (rollno,name,age,program) 
								values('".$rollno."','".$name."','".$age."','".$program."')";
						$mysqli->query($query);		
					}
					$html.="</table>";
					echo $html;
					echo "<br/>Data inserted in Database";
				
                    unlink($file);
                } else {
                    echo '<span class="msg">File not uploaded!</span>';
                }
        } else {
            echo '<span class="msg">Please upload excel sheet.</span>';
        }
    } else {
        echo '<span class="msg">Please upload excel file.</span>';
    }
}
?>

On successful execution, the data will be inserted in the database as in the given screenshot-

Excel store in database



Related Articles

PHP capitalize first letter
Age calculator in PHP
PHP Display PDF file from Database
Remove empty values from array PHP
Remove duplicates from array PHP
Floor function in PHP
Convert stdclass object to array PHP
How to read CSV file in PHP and store in MySQL
Generating word documents with PHP
PHP SplFileObject Examples
How to Upload a File in PHP
Simple PHP email form
Password reset system in PHP
HTTP authentication with PHP
PHP file cache library
PHP get current directory url
How to prevent CSRF attack in PHP
Forgot Password Script PHP mysqli database
PHP Contact Form with Google reCAPTCHA
HTML Form Validation in PHP
PHP sanitize input for MySQL
Simple pagination in PHP with MySQL
Store Emoji character in MySQL using PHP




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Simple PHP File Cache
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
How to print specific part of a web page in javascript
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Get Visitor\'s location and TimeZone
-----------------
Google Street View API Example
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
How to display PDF file in web page from Database in PHP
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.