使用PHPExcel将excel文件导入MySQL表

And*_*res 10 php mysql import phpexcel

好的,所以我已经能够让php显示excel .xls表中的数据但是这个相同的数据我想能够插入到我的表中.我似乎无法想出那部分,这是我到目前为止所得到的:

    $path = $_GET['file'];
include("../class/sql.php");
require '../class/PHPExcel.php';
require_once '../class/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($path);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
    $worksheetTitle     = $worksheet->getTitle();
    $highestRow         = $worksheet->getHighestRow(); // e.g. 10
    $highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $nrColumns = ord($highestColumn) - 64;
    echo '<br>Data: <table width="100%" cellpadding="3" cellspacing="0"><tr>';
    for ($row = 1; $row <= $highestRow; ++ $row) {

        echo '<tr>';
        for ($col = 0; $col < $highestColumnIndex; ++ $col) {
            $cell = $worksheet->getCellByColumnAndRow($col, $row);
            $val = $cell->getValue();
            if($row === 1)
            echo '<td style="background:#000; color:#fff;">' . $val . '</td>';
            else
                echo '<td>' . $val . '</td>';
        }
        echo '</tr>';
    }
    echo '</table>';
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,PHPExcel真棒,而且我没有时间阅读所有内容以完全理解:(我必须在星期三之前完成此操作..在此先感谢

编辑:这是它应该做的想法......价值部分是我不确定的.

$sql = "insert into tablename (col1, col2, col3) values(...)";
//start at row 2 so headers are not inserted
for ($row = 2; $row <= $highestRow; ++ $row) {

    for ($col = 0; $col < $highestColumnIndex; ++ $col) {
        $cell = $worksheet->getCellByColumnAndRow($col, $row);
        $val = $cell->getValue();
        //here's my prob..
        echo $val;
    }
    $result = mysql_query($sql);
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*Ruf 7

您应该创建一个数组并将其存储在数据库中,例如:

for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array()
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
    $cell = $worksheet->getCellByColumnAndRow($col, $row);
    $val[] = $cell->getValue();
    //here's my prob..
    //echo $val;
}

$sql="insert into tablename (col1, col2, col3) values(`".$val[0]."`, `".$val[1]."`, `".$val[2].")";
$result = mysql_query($sql);


}
Run Code Online (Sandbox Code Playgroud)