In the development of PHP programs, many times we will have the data to bulk Import database requirements, such as Student information batch added to the database, and in advance with Excel orchestration, Excel operation, is our more common choice.
In the operation of Excel, Phpexcelreade is a common choice for many people. In the implementation, we can upload the Excel file to a location in the server, by the following operations to import data from Excel into the database, the uploaded file will be deleted.
The code is as follows:
$dir=dirname(__file__);//gets the absolute path of the current script$dir=Str_replace(“//" ,"/", $dir)." /";$filename= ' Uploadfile.xls ';//You can define an uploaded file name $result=move_uploaded_file ($_files[' upload '] [' tmp_name '], $dir. $filename);//if uploaded to the current directory under if ($ Result)//If the upload file is successful, do import Excel operation {require_once ' phpexcelreader/excel/reader.php‘;$data=NewSpreadsheet_excel_reader ();$data->setoutputencoding (' utf-8′);//set the encoding of the output in the page, not utf8//The method automatically determines the file format that is uploaded, and does not meet the requirements to display an error message (the error message is inside the method). $data->read ("$filename”);//read the file that was uploaded to the current directory named $filename.error_reporting(E_all^E_notice);//if the Excel strap title is, start with $i=2 and remove the title section from the Excel table (to change the $i<= to $i< otherwise insert an extra empty data) for($i= 2;$i<$data->sheets[0][' NumRows '];$i++){$sql= "INSERT into user (Stuid,class, Name,sex,classnum,tel,addr,remark) VALUES (' ".$data->sheets[0][' cells ' [$i][1]. "', '". Study number $data->sheets[0][' cells ' [$i][2]. "',‘”.//class$data->sheets[0][' cells ' [$i][3]. "', '". Name $data->sheets[0][' cells ' [$i][4]. "',‘”.//Sex$data->sheets[0][' cells ' [$i][5]. "', '". Class serial number $data->sheets[0][' cells ' [$i][6]. "',‘”.//Contact Phone$data->sheets[0][' cells ' [$i][7]. "', '". Contact address $data->sheets[0][' cells '] [$i][8]. "')"; Note $db->query ($sql); $insert _info.= "$sql </br>/n"; Can be used to display data insert information} $totalNums = $data->sheets[0][' numrows ']-2;//to find the total number of imported data bars (here is the total data minus 2 to get rid of the headline)//echo "Import success! "; Unlink (" $filename "); Delete the uploaded excel file}else{$errmsg = "Upload Failed";}
How to import Excel data into MySQL via PHP