insertNewRow在使用 phpspreadsheet 之前不更改单元格名称的坐标

insertNewRowBefore using phpspreadsheet not change coordinate of cell name

提问人:Premlatha 提问时间:11/8/2023 更新时间:11/8/2023 访问量:33

问:

我有 excel 文件 3 行。我给第一行第一列起了名字。第三行是 。amount1=amount1+A2

200  ~ amount1
300
---
500
---

现在,我想在第 1 行之前插入一行,并将 setValue 添加到第 1 列。我使用phpspreadsheet来做到这一点。名称,不与值 200 一起到下一行。这会影响公式结果。amount1

new row  ~ amount1
200
300
---
error
---

代码如下:

require '../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
$reader         =\PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$spreadsheet    =$reader->load("File1.xlsx");
$sheet          =$spreadsheet->getActiveSheet();
$sheet->insertNewRowBefore(1);
$sheet->setCellValue('A1', 'new row');
$writer = new Xlsx($spreadsheet);
$writer->save('File1_output.xlsx');
php phpspreadsheet phpoffice-phpspreadsheet

评论


答:

0赞 Premlatha 11/8/2023 #1

从 getNamedRanges() 中,更新$range->setValue('Sheet1!$C$2');

Sheet1!$C$1->Sheet1!$C$2

require '../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
$reader         =\PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$spreadsheet    =$reader->load("File1.xlsx");
$sheet          =$spreadsheet->getActiveSheet();
$sheet->insertNewRowBefore(1);
$sheet->setCellValue('A1', 'new row');
 foreach ($spreadsheet->getNamedRanges() as $range) {
  if($range->getName()=='amount1'){
    $range->setValue('Sheet1!$C$2');
   }

  }
$writer = new Xlsx($spreadsheet);
$writer->save('File1_output.xlsx');