Laravel Excel动态标题行选择



我目前正在使用Laravel Excel包进行Laravel项目。

它工作得很好,除了一个我正在努力解决的用例,我现在正在努力解决几个小时。

我正在阅读的每个CSV文件都以标题行开头,这特别实用,但我的一些CSV文件以注释开头,如第1行的#CSV DD V2.4.3,然后是第2行的标题行。

因此,我需要了解如何确定标题行所在的实际行,以避免出现不需要的行。我特别需要让它在WithHeadingRow接口实现的headingRow((方法中工作。有没有办法从csv文件中抓取行来确定正确的标题行?

希望你能发现,提前谢谢

我会考虑分两步来完成。这是一个非常一般的例子,因此您需要添加适当的Laravel Excel导入问题和其他依赖项,执行任何检查以确保文件存在,等等

  1. 在开始导入之前检查文件的第一行,以确定正确的标题行
// get the first line of the file
$line = fgets(fopen('path/to/file.csv', 'r'));
// set the heading row based on the line contents
// add terms to search array if desired ['#CSV','...']
$heading_row = Str::startsWith(trim($line), ['#CSV']) ? 2 : 1;
  1. 使用WithHeadingRow关注点和关联方法动态注入标题行值
class SampleImport implements WithHeadingRow
{
private $heading_row;
// inject the desired heading row or default to first row
public function __construct($heading_row = 1)
{
$this->heading_row = $heading_row;
}
// set the heading row
public function headingRow(): int
{
return $this->heading_row;
}    
}

现在,您可以在运行导入时传递自定义标题行。

Excel::import(new SampleImport($heading_row), 'path/to/file.csv');

最新更新