Laravel Excel 动态标题行选择

Laravel Excel Dynamic Heading Row selection

我目前正在使用 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');