PHP |电子表格 |通过坐标设置单元格值
setCellValue()函数是 PHPSpreadsheet 中的内置函数,用于设置电子表格中单元格的值。
句法:
setCellValue( $coordinate, $value )
参数:该函数接受上面提到的两个参数,如下所述:
- $coordinate:该参数用于存储excel表格的坐标值。
- $value:此参数用于存储要在 Excel 表中设置的数据的值。
返回值:此函数返回类 PhpOffice\PhpSpreadsheet\Worksheet\Worksheet 的对象。
示例 1:
PHP
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');
?>
PHP
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');
?>
输出:
或者,可以通过先检索单元格对象然后设置值来实现。为此,可以借助getCell()函数检索 Cell 对象,然后借助setValue()函数设置值。
句法:
$spreadsheet->getActiveSheet()->getCell($coordinate)->setValue($value);
示例 2:
PHP
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');
?>
输出:
参考: https://phpspreadsheet.readthedocs.io/en/develop/topics/accessing-cells/