0

I want to read the excel file and write the data in the next cell simultaneously.

I am using the PhpSpreadsheet library Github. What I had tried is

$inputFileType = 'Xlsx';
$inputFileName = 'phones.xlsx';
$sheetname = 'sheet1';

/**  Identify the type of $inputFileName  **/
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName);

/**  Create a new Reader of the type that has been identified  **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);


/**  Load $inputFileName to a Spreadsheet Object  **/
$spreadsheet = $reader->load($inputFileName);

/**  Convert Spreadsheet Object to an Array for ease of use  **/
$schdeules = $spreadsheet->getActiveSheet()->toArray();

foreach( $schdeules as $single_schedule )
{               
    echo '<div class="row">';
    foreach( $single_schedule as $key => $single_item )
    {
        if($_REQUEST['inbound_phone_no'] == $single_item){
            // echo $key;exit;
            
// I am trying to write the data using this but nothing is going on.
$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow(0, 3, 'PhpSpreadsheet');


            echo '<p class="item">Phone No Exist: ' . $single_item . '</p>';
        }else{
            echo '<p class="item">' . $single_item . '</p>';
        }
    }
    echo '</div>';
}

exit;

I want to write some value if the request data and the value in the cell match, then update the status by writing 1 or 2 in the next empty cell of the sheet. The excel file image is

enter image description here

I am new to this library. So please ignore it if it's a newbie question. I had looked into the questions

Read Xlsx file in PhpSpreadsheet and How to add new row on Excel using PHPSpreadsheet

The help on this will highly be appreciated.

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
NomanJaved
  • 1,324
  • 17
  • 32

1 Answers1

1

as the ->load loads the xlsx to memory, you change values in copy in memory.

the complete way is something like that:

$fileExcel          = 'load.xlsx';
$target_dir         = 'save.xlsx';
$reader             = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet        = $reader->load($fileExcel);
$sheet              = $spreadsheet->getActiveSheet();
$lsValue            = $sheet->getCell('A1')->getValue();
$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow(0, 3, 'PhpSpreadsheet');
$writer = new  \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($target_dir);

so you need the last 2 lines to save the file before your exit:

$writer = new  \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($target_dir);
FatFreddy
  • 1,160
  • 1
  • 9
  • 16