Import data from Excel to mysql database using PHPExcel
|Earlier I wrote a post – how to import excel sheet data to mysql database using PHP.
That was by using PHPExcelreader API. This time, I am writing this tutorial again now using PHPExcel library.
I came to know that many new developers are searching for many ways or API to import excel data to MySQL database.
So, first, we download the Phpexcel API. You can download this from https://phpexcel.codeplex.com/ .
PHPExcel library is used to read and write from different excel formats like .xls, csv, ods etc. I am not going into details here about i. I will explain only how to import excel file in MySQL database using PHP.
First, download the PHPExcel library –https://phpexcel.codeplex.com/
Second, create a form to upload the excel sheet. You can use the same form as in the previous excel sheet import example.
Here is the PHP code –
Note – Don’t forget to include the database connection file.
<?php /****** Include the EXCEL Reader Factory ***********/ error_reporting(0); set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/'); include 'PHPExcel/IOFactory.php';
Once you download the PHP excel API, you will get a folder name Classes.
We will use only this folder for importing the excel file. Please keep this folder in the root of your code.
In below code, we checked the uploaded excel file and we checked it is excel file or not.
if(isset($_POST) && !empty($_FILES['excelupload']['name'])) { //print_r($_FILES['excelupload']); $namearr = explode(".",$_FILES['excelupload']['name']); if(end($namearr) != 'xls' && end($namearr) != 'xlsx') { echo '<p> Invalid File </p>'; $invalid = 1; }
Below code shows that if it is excel file, then we move excel file to uploads folder. It is necessary to move the excel file on the same server to upload.
if($invalid != 1) { $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["excelupload"]["name"]); $response = move_uploaded_file($_FILES['excelupload']['tmp_name'],$target_file); // Upload the file to the current folder
Below code upload the excel file from local system to server and upload. $allDataInSheet variable contain the all excel data in an array.
if($response) { try { $objPHPExcel = PHPExcel_IOFactory::load($target_file); } catch(Exception $e) { die('Error : Unable to load the file : "'.pathinfo($_FILES['excelupload']['name'],PATHINFO_BASENAME).'": '.$e->getMessage()); } $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); //print_r($allDataInSheet); $arrayCount = count($allDataInSheet); // Total Number of rows in the uploaded EXCEL file //echo $arrayCount;
Below query insert excel sheet data to MySQL database table. By using the below method, any number of fields can be inserted in MySQL database.
$string = "INSERT INTO `table1` (`Sr.No.`,`Emp ID`, `Name`, `Address`) VALUES "; for($i=2;$i<=$arrayCount;$i++){ $empid= trim($allDataInSheet[$i]["B"]); $name = trim($allDataInSheet[$i]["C"]); $address = trim($allDataInSheet[$i]["D"]); $string .= "( '' , '".$empid."' , '".$name ."','".$address ."', ),"; } $string = substr($string,0,-1); //echo $string; mysql_query($string); // Insert all the data into one query } }// End Invalid Condition echo "<div style='color:#3C7C64'>Import Succesful</div>"; } ?>
Please write in a comment for any issue.
If you find it difficult then you can move to another option – How to import excel data to mysql database using php .
If anyone’s code is not working, then please send me a message I will try to help you out. Thanks for reading..:-)
code Not working..
where you are facing problem?
firstly i want to import and export data into the DB with xls file,
data is coming in xls file when i export
BUT
xls file is getting uploaded on server but the data is not going in database!
Please help.
if your file is getting uploaded then half of your work done. i think u are missing something.
Please check, have u included these –
set_include_path(get_include_path() . PATH_SEPARATOR . ‘Classes/’);
include ‘PHPExcel/IOFactory.php’;
check database connection
target file path..
comment error_reporting to check what error is coming..
I have the same problem. The file is uploaded but do not want to import to sql. I change here mysql_query($string,$conn ); // Insert all the data into one query i put connection.
This shows real exepstire. Thanks for the answer.
a question !:
as I can dynamically delete rows in the Excel file if it is empty a cell in any column of the document. Also if you can check for duplicate fields in a column and delete rows and insert it into the database.
I’m using the library PHPExcel
well thanks for your time and help!.
Yes, you can delete duplicate rows and insert into database by writing some code but why don’t u use excel property of removing duplicates. It will be easier and can be done by click only. then you don’t need to write extra code. Thanks
Thanks K Gaurav
For the suggestion perfect !. but what if I need to create the code to delete rows that have an empty field in any column excel file any idea, how to encode it, could show me the code necessary.
well thanks for your time and help!.
nice
Thak u so much. now i got results
my code is working but data is not inserting in database and if i had even not choose any file then also it showing imported successfully
please help.
Enable the php errors and see what is happening in code..check the uploads folder, Give it a try with some debugging
Weclome..:)
thanks:)
Hi, nice tutorial there, do you know why im getting the "Notice: Undefined index: A, B, C"? the A error reference to this line trim($allDataInSheet[$i]["A"])
Can you add downloadable working demo? (php code + sql + test.xls) thank you
this is the error which is throwing..
check the manual that corresponds to your MySQL server version for the right syntax to use near ”school’ (id,email, name) VALUES
Thank you very much, I was having so much trouble but your code works perfectly!
hi, I m trying to import excel file but why it is not importing more than 3 coloumns
why i got blanked page, and i checked my database the data didn’t fill too
Can you please help me out, i am facing some error while uploading excel sheet. Thanks
great work, i appreciate.. so much.
Thanks for appreciating.
thanks for share this source code, helpfull
welcome ..
Thanks for sharing.