在 PHPSpreadsheet 导入中跳过第一行

刚刚开始使用 phpspreadsheet。我试图弄清楚如何在上传时跳过 Excel 文件中的标题行。


require '../vendor/autoload.php';

if (pathinfo($_FILES['upexcel']['name'], PATHINFO_EXTENSION) == 'csv') {

  $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();

} else {

  $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();

}

$spreadsheet = $reader->load($_FILES['upexcel']['tmp_name']);


$worksheet = $spreadsheet->getActiveSheet();

$sql = "INSERT INTO `testCommission` (`One`, `two`, `three`, `four`, `five`, `six`, `seven`) VALUES (?, ?, ?, ?, ?, ?, ?)";

foreach ($worksheet->getRowIterator() as $row) {

  // Fetch data

  $cellIterator = $row->getCellIterator();

  $cellIterator->setIterateOnlyExistingCells(false);

  $data = [];

  foreach ($cellIterator as $cell) {

    $data[] = $cell->getValue();

  }

我可以用上面的脚本做什么来实现这个目标?


一只甜甜圈
浏览 161回答 2
2回答

HUH函数

您需要检测,当它是第一行时,像这样的二进制变量会有所帮助<?phprequire '../vendor/autoload.php';if (pathinfo($_FILES['upexcel']['name'], PATHINFO_EXTENSION) == 'csv') {&nbsp; $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();} else {&nbsp; $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();}$spreadsheet = $reader->load($_FILES['upexcel']['tmp_name']);$worksheet = $spreadsheet->getActiveSheet();$sql = "INSERT INTO `testCommission` (`One`, `two`, `three`, `four`, `five`, `six`, `seven`) VALUES (?, ?, ?, ?, ?, ?, ?)";$isheader = 0;foreach ($worksheet->getRowIterator() as $row) {&nbsp; // Fetch data&nbsp; if($isheader > 0) {&nbsp; &nbsp; &nbsp; $cellIterator = $row->getCellIterator();&nbsp; &nbsp; &nbsp; $cellIterator->setIterateOnlyExistingCells(false);&nbsp; &nbsp; &nbsp; $data = [];&nbsp; &nbsp; &nbsp; foreach ($cellIterator as $cell) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $data[] = $cell->getValue();&nbsp; &nbsp; &nbsp; }&nbsp; } else&nbsp;&nbsp; { $isheader = 1; }}?>

哔哔one

使用过滤器类。不要忘记自动加载:require_once ( 'vendor/autoload.php' );创建过滤器:class FirstRowFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter{    public function readCell($column, $row, $worksheetName = '') {        //  Return true for rows after first row        return $row > 0;    }}适用于读者:$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");$filterRow = new FirstRowFilter();$reader->setReadFilter($filterRow);加载文件:$spreadsheet = $reader->load($file);读取器将仅加载指定行之后的行。
打开App,查看更多内容
随时随地看视频慕课网APP