为了账号安全,请及时绑定邮箱和手机立即绑定

在 PHPSpreadsheet 导入中跳过第一行

在 PHPSpreadsheet 导入中跳过第一行

PHP
一只甜甜圈 2023-09-15 14:39:14
刚刚开始使用 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();  }我可以用上面的脚本做什么来实现这个目标?
查看完整描述

2 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

您需要检测,当它是第一行时,像这样的二进制变量会有所帮助


<?php

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 (?, ?, ?, ?, ?, ?, ?)";

$isheader = 0;

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

  // Fetch data

  if($isheader > 0) {

      $cellIterator = $row->getCellIterator();

      $cellIterator->setIterateOnlyExistingCells(false);

      $data = [];

      foreach ($cellIterator as $cell) {

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

      }

  } else 

  { $isheader = 1; }

}

?>


查看完整回答
反对 回复 2023-09-15
?
哔哔one

TA贡献1854条经验 获得超8个赞

使用过滤器类。

不要忘记自动加载:

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);

读取器将仅加载指定行之后的行。


查看完整回答
反对 回复 2023-09-15
  • 2 回答
  • 0 关注
  • 141 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信