Laravel Excel 将导入视为一个实例化,该实例化在同一实例化中循环遍历文件的所有行。所以当你这样做时:
Excel::import(new CountryImport, $request->country_data);
(其中 $request->country_data 是您的文件),然后您可以在导入中对其运行条件逻辑。
例如,如果您想将其保存到数据库中,您可以使用
ToModel
实现:
use Maatwebsite\Excel\Concerns\ToModel;
class CountryImport implements ToModel
那么你的其余代码可能看起来与此类似:
public $countryColumns = [];
public $countryColumnAbbreviations = [];
public $currentRow = 0;
public function model (array $row){
$rowColumnIndex = 0;
while($row[$rowColumnIndex] != ""){
if($this->currentRow == 0){
if($rowColumnIndex > 0){
$this->countryColumns[$rowColumnIndex] = $row[$rowColumnIndex];
}
}
else if($this->currentRow == 1){
if($rowColumnIndex > 0){
$this->countryColumnAbbreviations[$rowColumnIndex] = $row[$rowColumnIndex];
}
} else {
return new CountryDatabaseEntry([
'country_name' => $this->countryColumns[$rowColumnIndex],
'country_code' => $this->countryColumnAbbreviations[$rowColumnIndex],
'weight' => $row[0],
'rate' => $row[$rowColumnIndex]
]);
}
$rowColumnIndex++;
}
$this->currentRow++;
}
那么这段代码中发生了什么?我正在使用
$currentRow
跟踪当前行。从那里开始,如果当前行等于零(第一行),则我们循环遍历 $row
列(由 lara-excel 提供),直到找到空字符串。这表明列标题已结束并且您已离开国家/地区。每个标头将其值附加到 countryColumns
数组中。如果当前行等于 1,则逻辑完全相同,只不过我们将其附加到 countryColumnsAbbreviations
数组中。因为我们使用 $rowColumnIndex
显式分配数组键,所以一切都应该始终一致。然后,如果当前行不是 0 或 1,我们使用 $row[0]
来获取权重,因为权重始终位于第一列中,然后根据我们当前迭代的列添加速率。
当然,因为我没有您的 csv 之一可供测试,所以我无法完全验证此代码的功能,但我认为它可以让您顺利上路。您可能比我更有创意,通过用短代码键入名称,仅使用 1 个数组来表示国家及其代码,但为了可读性和时间考虑,我只是提供了我在这里选择的解决方案。让我知道这是否有帮助!