如何在PhpSpreadSheet中添加新行?

时间:2019-06-10 12:30:49

标签: php phpspreadsheet

我试图在PhpSpreadsheet中添加新行,但发生此错误:

(1/1) FatalThrowableError
Type error: Argument 1 passed to Maatwebsite\Excel\Sheet::fromArray() must be an instance of Maatwebsite\Excel\Concerns\FromArray, array given, called in /home/bruno/Documentos/Sistemas/atualizacao_sistema/ambev_heva/app/Exports/EventExport.php on line 270

行代码:

$item_values = [
'ITEM1','ITEM2','ITEM3','ITEM4'
];
$sheet->fromArray([$item_values],NULL,'A'.$lineStart);

编辑:我忘了说我使用Maatwebsite \ Excel

代码:

class EventExport implements FromView, WithEvents
{....

    public function registerEvents(): array
    {

        $event = $this->getEvent();

        // TODO: Implement registerEvents() method.
        return [

            AfterSheet::class => function(AfterSheet $afterEvent) use ($event){

                /** @var Sheet $sheet */
                $sheet = $afterEvent->sheet;
                .....
                $sheet->fromArray([$item_values],NULL,'A35');


                //Aplicar mudanças
                $afterEvent->sheet = $sheet;
            }
        ];
    }

1 个答案:

答案 0 :(得分:0)

如果您不使用数组,则可以手动设置单元格:

$reader =  \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load('<Path>'); // add here the Path to the Excel to read
$sheet = $spreadsheet->getActiveSheet(); 
$rows = 8;     // row count
$colums = 8;   // column count
$valuearray = array(array());// Add here the Values
$counti=1;
while ($rows >= $counti) {
    $countj=0;
    while ($colums>= $countj) {

        $col=chr(65+$countj); //calc Column number
        $sheet->setCellValue($col.rows , $valuearray[i][j]); //Write cells
        $spreadsheet->getActiveSheet()->getStyle($col.$rows)->getAlignment()->setWrapText(true); //set wrap for newlines in cells
        $countj++;
    }
    $counti++;  
}

如果要插入一行,请使用

$sheet->insertNewRowBefore($row, 1);