如何使用 Laravel Excel 将 Excel 导入数据库

问题描述

我需要使用 Laravel Excel 库将考勤报告导入我的系统,但我在数据验证错误方面遇到了一些问题。例如,我有以下 excel 数据要导入到我的数据库中。

enter image description here

如您所见,John 已将手指插入机器三次,但我只想使用 Laravel excel 库将第一条和最后一条记录插入到我的数据库中。而且我的数据库的结构如下图所示。

enter image description here

如您所见,在我的数据库结构中,我的 time_in 和 time_out 在同一行,但在 excel 文件中 time_in 在一行中,time_out 在另一行中,那么我如何正确插入这个 excel 文件我的数据库

解决方法

您需要在将数据发送到数据库 (DB) 之前对其进行解析,而不仅仅是将其直接提供给您的数据库。 一个简单的以 public static void main(String[] args) throws IOException { URL url = new URL(args[0]); URLConnection connection = url.openConnection(); connection.addRequestProperty("Accept","image/png,image/*;q=0.8,*/*;q=0.5"); try (FileOutputStream outputStream = new FileOutputStream(new File(args[1])); InputStream inputStream = connection.getInputStream()) { byte[] bytes = new byte[2048]; int numBytesRead; while ((numBytesRead = inputStream.read(bytes)) != -1) { outputStream.write(bytes,numBytesRead); } } catch (Exception e) { e.printStackTrace(); } } 为分隔符的 explode 可以拆分 ' ' 列,然后使用 Date/Time 格式化日期和时间,同时继续跟踪您需要的数据为 { {1}} 和 DateTime

假设: Time In

Time Out $date = explode(' ',$dateTime);

假设日期是 $date[0] = the date,2/1/2021$date[1] = the time,7:31 可以填写为 j/n/Y

,

可能是您必须先解析数据才能将其存储到数据库中 或者您可以更改 Excel 文件内容