我需要使用PHPExcel将excel文件导入到sql服务器表中,我在Google上进行了搜索,但找不到正确,快速的解决方案,因此任何机构都可以通过一些代码或示例为我提供帮助, 最好的问候
答案 0 :(得分:1)
PHPExcel已弃用。
PhpSpreadsheet是使用核心PHP 的另一种选择。
如果您使用 laravel ,也许Laravel-Excel是最好的选择。
开始竞猜 Laravel-Excel
use Excel;
use File;
class Test extends Controller{
public function importToDB(){
$fileinfo = 'path/test.xls';//your file path
if (File::exists(fileinfo)) {
Excel::selectSheets('sheetName')->load(fileinfo, function ($results) {//Excel worksheet name
$columOne = $results->takeColumns(1)->toArray();//Array data
$columTwo = $results->takeColumns(2)->toArray();
foreach($columOne as $key => $name){//Single item
// insert into database
}
}, false);
}
}
答案 1 :(得分:0)
我使用此代码,但给我一个错误: SQLSTATE:42000 编码:156 消息:[Microsoft] [用于SQL Server的ODBC驱动程序13] [SQL Server]关键字“文件”附近的语法不正确。
$serverName = "HREXPRESS";
$connectionInfo = array( "Database"=>"hrexpress"/* "UID"=>"username",
"PWD"=>"password"*/ );
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
include "$_SERVER[DOCUMENT_ROOT]/Classes/PHPExcel.php";
include "$_SERVER[DOCUMENT_ROOT]/Classes/PHPExcel/IOFactory.php";
//load excel file using PHPExcel's IOfactory
$excel = PHPExcel_IOFactory::load('file2.xls');
//set active sheet to first sheet
$excel->setActiveSheetIndex(0);
echo "<table>";
echo "
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>age</th>
</tr>
";
//first row of data series
$i = 1 ;
//loop until the end of data series(cedll contains empty string)
while($excel->getActiveSheet()->getcell('A'.$i)->getValue() != ""){
//get cells value
$id = $excel->getactiveSheet()->getCell('A'.$i)->getValue();
$first = $excel->getactiveSheet()->getCell('B'.$i)->getValue();
$last = $excel->getactiveSheet()->getCell('C'.$i)->getValue();
$age = $excel->getactiveSheet()->getCell('D'.$i)->getValue();
$q = "INSERT INTO dbo.file (id,first,last,age) VALUES ('$id','$first','$last','$age')";
$d = sqlsrv_query($conn,$q);
//echo
echo "
<tr>
<td>".$id."</td>
<td>".$first."</td>
<td>".$last."</td>
<td>".$age."</td>
</tr>
";
//and DON'T FORGET to increment the row pointer ($i)
$i++;
}
echo "</table>";
//echo error
if( $d === false ) {
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "</br>SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}