简体   繁体   中英

PHP looping through excel cells

Hello i'm trying to extract some data from an excel file using Spreadsheet php, but it's not working and not filling the array with extracted data.

My code:

$request->validate([
    'uploaded_file' => 'required|file|mimes:xls,xlsx'
]);

$excel_file = $request->file('uploaded_file');
$file = IOFactory::load($excel_file->getRealPath());

$worksheet = $file->getActiveSheet();


$data_grid = []; 
$data_detail = [];

$data_grid['codice_cliente'] = $file->getActiveSheet()->getCell('B3')->getValue();
$data_grid['codice_destinazione'] = $file->getActiveSheet()->getCell('G3')->getValue();
$data_grid['data_ordine'] = '2022-07-15 15:32:04';
$data_grid['data_richiesta'] = '2022-06-15';
$data_grid['note_consegna'] = $file->getActiveSheet()->getCell('G5')->getValue();
$data_grid['id_agente'] = Auth::user()->id;
$data_grid['canale'] = 'B';
$data_grid['tipologia'] = 'O';
$data_grid['edi_id'] = 1;
$data_grid['edi_company'] = 'C';
$data_grid['edi_doctype'] = 'D';
$data_grid['jde_id'] = 2;
$data_grid['jde_company'] = 'E';
$data_grid['jde_doctype'] = 'F';
$data_grid['stato_ordine'] = 1;
$data_grid['total_order'] = 99.99;
$data_detail['nr_riga'] = 50;


$row = 8;
foreach($worksheet as $data) {
    
    $row++;
    
    $data_detail['codice_articolo'] = $data->getCell("A$row")->getValue();
    $data_detail['quantita'] = $data->getCell("B$row")->getValue();
    $data_detail['prezzo'] = $data->getActiveSheet()->getCell("C$row")->getValue();
}

The foreach loop has to extract all values from those specific columns for each row.. but i get array key error.

Excel: 在此处输入图像描述

Your foreach loop doesn't make sense. Just use a for loop and it's $worksheet->getCell() , rather than $data->getCell()

$worksheet = $file->getActiveSheet();

...

$highestRow = $worksheet->getHighestRow();

for($row = 8; $row < $highestRow; $row++) {
    $data_detail['codice_articolo'] = $worksheet->getCell("A$row")->getValue();
    $data_detail['quantita'] = $worksheet->getCell("B$row")->getValue();
    $data_detail['prezzo'] = $worksheet->getActiveSheet()->getCell("C$row")->getValue();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM