Home >Backend Development >PHP Tutorial >Use PHP to import excel (xls) files into mysql database_PHP tutorial
A customer contacted me last night to build a website. The request was to import the data in the excel file provided by the customer into a mysql database. The most common method is to first export the xls file into a csv format file. Then parse the csv format file and import it into the mysql database. The method is relatively redundant and is divided into several steps, which is very inconvenient. Today Broken Bridge Canxue introduced a method that directly skips the intermediate link of csv and directly imports the excel file into the mysql database.
First we need to download PHP-ExcelReader. This is an open source project, mainly used to parse excel files. Download address: http://sourceforge.net/projects/phpexcelreader. Unzip it after downloading. It is mainly used There are two files in the excel folder, reader.php and oleread.php (the default for this file is oleread.inc, I don’t know why, it’s a bunch of e-texts, I haven’t read them, just change the name).
Find the following similar code in the reader.php file (the first line is) and change it to the correct oleread.php path: require_once 'oleread.php';
Then create a new one The php file imports reader.php, the code is as follows:
require_once 'Excel/reader.php';
$data = new Spreadsheet_Excel_Reader();
$data-> ;setOutputEncoding('gbk');\Set the encoding here, usually in gbk mode
$data->read('Book1.xls');//File path
error_reporting (E_ALL ^ E_NOTICE);
//Here I will only loop the contents of the excel file. To store it in the database, just write a mysql statement in the output place ~
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
for ($j = 1; $j <= $data->sheets[0][' numCols']; $j++) {
echo """.$data->sheets[0]['cells'][$i][$j]."",";
}
echo "n";
}
?>
Note: Please do not use the xls in the PHP-ExcelReader compressed package for testing. Broken Bridge Canxue found that the file cannot be opened even with excel. So it is wrong.
Broken Bridge Canxue used the above method to parse a 1.4M data, and it all showed normal, so everyone can use it with confidence
Original text: http://www.js8.in/618.html