使用 Phpspreadsheet 将列作为行从 Excel 插入到 mysql
Insert column as row from Excel to mysql usng Phpspreadsheet
不确定如何设置标题格式。对不起。
我正在使用 PhpSpreadsheet 到 INSERT
将 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 |
+----+----+----+----+----+----+
下面的代码片段可能会有所帮助:
...
$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);
}
...
不确定如何设置标题格式。对不起。
我正在使用 PhpSpreadsheet 到 INSERT
将 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 |
+----+----+----+----+----+----+
下面的代码片段可能会有所帮助:
...
$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);
}
...