我对将Excel单元格数据导入sqlserver数据库有疑问。但是我的Excel数据如下所示:
ID|NAME |DAY1 |DAY2 |DAY3 |DAY4 |
--+--------+-------+-------+-------+-------+
1 |John Doe|shift-1|shift-1|shift-1|shift-1|
--------------------------------------------
2 |Alex |shift-2|shift-2|shift-2|shift-2|
--------------------------------------------
3 |McArthur|shift-3|shift-3|shift-3|shift-3|
--------------------------------------------
我的数据库格式在下面看起来很幸运:
DateTime|ID|NAME |SCHEDULE|
--------+--+--------+--------+
DAY1 |1 |John Doe|Shift-1 |
------------------------------
DAY1 |2 |Alex |Shift-2 |
------------------------------
DAY1 |3 |McArthur|Shift-3 |
------------------------------
DAY2 |1 |John Doe|Shift-1 |
------------------------------
DAY2 |2 |Alex |Shift-2 |
------------------------------
DAY2 |3 |McArthur|Shift-3 |
------------------------------
DAY3 |1 |John Doe|Shift-1 |
------------------------------
DAY3 |2 |Alex |Shift-2 |
------------------------------
DAY3 |3 |McArthur|Shift-3 |
------------------------------
DAY4 |1 |John Doe|Shift-1 |
------------------------------
DAY4 |2 |Alex |Shift-2 |
------------------------------
DAY4 |3 |McArthur|Shift-3 |
然后我尝试写了一个代码,然后偏离了代码。
$fp = fopen($_FILES['csv']['tmp_name'],'r') or die("Can't Open");
while($csv_line = fgetcsv($fp,1024))
{
$cnt = count($csv_line);
for($i=1;$i<=$cnt;$i++){
$data[$i]['ID'] = $csv_line[1];
$data[$i]['NAME'] = $csv_line[2];
$data[$i]['DAY1'] = $csv_line[3];
$data[$i]['DAY2'] = $csv_line[4];
$data[$i]['DAY3'] = $csv_line[5];
$data[$i]['DAY4'] = $csv_line[6];
}
return $data;
}
fclose($fp) or die("Error");
有可能做到吗?因为我的公司不想更改旧的excel格式,因为它将影响所有分支机构。
答案 0 :(得分:1)
由于您需要按日值对数据进行分组,因此您也需要以这种方式组织循环,即从文件中读取的每一行每天创建一个条目。像这样:
$data = array();
while($csv_line = fgetcsv($fp,1024)) {
$data[] = array('DATETIME' => 'DAY1', 'ID' => $csv_line[0], 'NAME' => $csv_line[1], 'SCHEDULE' => $csv_line[2]);
$data[] = array('DATETIME' => 'DAY2', 'ID' => $csv_line[0], 'NAME' => $csv_line[1], 'SCHEDULE' => $csv_line[3]);
$data[] = array('DATETIME' => 'DAY3', 'ID' => $csv_line[0], 'NAME' => $csv_line[1], 'SCHEDULE' => $csv_line[4]);
$data[] = array('DATETIME' => 'DAY4', 'ID' => $csv_line[0], 'NAME' => $csv_line[1], 'SCHEDULE' => $csv_line[5]);
}
然后,您应该能够将$data
数组的每一行插入到数据库中,例如
foreach ($data as $d) {
// insert $d into database
}
答案 1 :(得分:0)
您可以使用 Unpivot 获得所需的结果。但这在数据库端起作用。首先,您需要将该记录放入数据库中,然后使用Unpivot将记录转换为所需格式。
GO
SELECT [datetime], id, name, schedule
FROM
(SELECT id, name, Day1, day2, day3, day4
FROM pvt) p
UNPIVOT
(schedule FOR [datetime] IN
(Day1, day2, day3, day4)
)AS unpvt;
GO
您可以使用此输出将其插入表中。