【问题标题】:Insert column as row from Excel to mysql usng Phpspreadsheet使用 Phpspreadsheet 将列作为行从 Excel 插入到 mysql
【发布时间】:2020-03-02 16:28:18
【问题描述】:

不确定如何格式化标题。原谅我。
我正在使用PhpSpreadsheetINSERT 将Excel 列导入MySql 数据库。

我有什么

我尝试了什么

...

$activeSheet = $spreadsheet->getActiveSheet();
$sheetData = $activeSheet->toArray();

foreach($sheetData as $row) {
    $col1 = $row[0];

    $sql = "INSERT INTO rowascol (n1) VALUES ($col1)";
    $query = mysqli_query($con, $sql);
}

...

我得到了什么

+----+----+----+----+----+----+
| id | n1 | n2 | n3 | n4 | n5 |
+----+----+----+----+----+----+
|  1 |  4 |    |    |    |    |
|  2 |  6 |    |    |    |    |
|  3 | 45 |    |    |    |    |
|  4 |  5 |    |    |    |    |
|  5 |  7 |    |    |    |    |
+----+----+----+----+----+----+

我想要什么

+----+----+----+----+----+----+
| id | n1 | n2 | n3 | n4 | n5 |
+----+----+----+----+----+----+
|  1 |  4 |  6 | 45 |  5 |  7 |
|  2 |  9 |  3 |  5 |  8 | 12 |
+----+----+----+----+----+----+

【问题讨论】:

    标签: php mysql phpspreadsheet


    【解决方案1】:

    下面这段代码 sn-p 可能会有所帮助:

    ...
    
    $highestColumn= ord($activeSheet->getHighestColumn())- ord('A') + 1;
    
    for ($col = 0; $col < $highestColumn; $col++) {
        $col1 = array();
        foreach($sheetData as $row) {
            array_push($col1, $row[$col]);
        }
        $col1 = implode(',', $col1);
    
        $col1 = $col + 1 . ',' . $col1;  // add id
        $sql = "INSERT INTO rowascol VALUES ($col1)";
        // echo $sql;
        $query = mysqli_query($con, $sql);
    }
    
    ...
    

    【讨论】:

    • 这里没有“最后一个逗号”问题。
    猜你喜欢
    • 1970-01-01
    • 2018-02-12
    • 2020-09-21
    • 2018-11-05
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    相关资源
    最近更新 更多