Friday, October 24, 2025
HomeLanguagesPHP | Spreadsheet | Setting a cell value by coordinate

PHP | Spreadsheet | Setting a cell value by coordinate

The setCellValue() function is an inbuilt function in PHPSpreadsheet which is used to set the value of a cell in a spreadsheet.

Syntax: 

setCellValue( $coordinate, $value )

Parameters: This function accepts two parameters as mentioned above and described below:  

  • $coordinate: This parameter is used to store the value of the coordinate of the excel sheet.
  • $value: This parameter is used to store the value of data which is to be set in an excel sheet.

Return Value: This function returns Object of class PhpOffice\PhpSpreadsheet\Worksheet\Worksheet.

Example 1:  

PHP




<?php
 
// require_once('path/vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  
// Creates New Spreadsheet
$spreadsheet = new Spreadsheet();
 
// Retrieve the current active worksheet
$sheet = $spreadsheet->getActiveSheet();
 
// Sets cell A1 with String Value
$sheet->setCellValue('A1', 'GeeksForGeeks!');
 
// Sets cell A2 with Boolean Value
$sheet->setCellValue('A2', TRUE);
 
// Sets cell B1 with Numeric Value
$sheet->setCellValue('B1', 123.456);
 
// Write an .xlsx file
$writer = new Xlsx($spreadsheet);
 
// Save .xlsx file to the current directory
$writer->save('gfg1.xlsx');
?>


Output: 

gfg1.xlsx

Alternatively, It can be achieved by retrieving the cell object firstly and then set the value. For this purpose, Cell object can be retrieved with the help of getCell() function, and then the value can be set with the help of setValue() function. 

Syntax:  

$spreadsheet->getActiveSheet()->getCell($coordinate)->setValue($value);

Example 2:  

PHP




<?php
 
// require_once('vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 
// Creates New Spreadsheet
$spreadsheet = new Spreadsheet();
 
// Retrieve the current active worksheet
$sheet = $spreadsheet->getActiveSheet();
 
// Sets cell A1 with String Value
$sheet->getCell('A1')->setValue('GeeksForGeeks!');
 
// Sets cell A2 with Boolean Value
$sheet->getCell('A2')->setValue(TRUE);
 
// Sets cell B1 with Numeric Value
$sheet->getCell('B1')->setValue(123.456);
 
// Write an .xlsx file
$writer = new Xlsx($spreadsheet);
 
// Save .xlsx file to the current directory
$writer->save('gfg2.xlsx');
?>


Output: 

gfg2.xlsx

Reference: https://phpspreadsheet.readthedocs.io/en/develop/topics/accessing-cells/
 

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS