SpreadSheet-Coding.com

PHPSpreadsheet · Google Sheets API · Excel

Spreadsheets, driven by code.

Hands-on PHP tutorials for working with Excel and Google Sheets — read and write .xlsx, convert files to JSON, stream downloads in the browser, and insert images, formulas, and styling. Every guide ships with code you can copy, run, and adapt.

append-google-sheets-rows.php View article
<?php

require 'vendor/autoload.php';

use Google\Client;
use Google\Service\Sheets;
use Google\Service\Sheets\ValueRange;

/**
 * Set up parameters.
 */
$spreadsheetId = 'Your spreadsheetId here.';
$keyFile = 'service-account.json';
$range = 'Sheet1!A1';
$valueInputOption = 'RAW';
$insertDataOption = 'INSERT_ROWS';

$client = new Client();
$client->setApplicationName('Append Google Sheets Rows');
$client->setAuthConfig($keyFile);
$client->addScope(Sheets::SPREADSHEETS);

$service = new Sheets($client);

$newRows = [
    ['N1', 'n1@example.com', '2026-08-12', 'Pro'],
    ['N2', 'n2@example.com', '2026-08-13', 'Free'],
    ['N3', 'n3@example.com', '2026-08-14', 'Team'],
];

$response = $service->spreadsheets_values->append(
    $spreadsheetId,
    $range,
    new ValueRange(['values' => $newRows]),
    [
        'valueInputOption' => $valueInputOption,
        'insertDataOption' => $insertDataOption,
    ]
);

// The API found the table itself. Ask it what it found, and where it wrote.
printf("Range we asked for : %s\n", $range);
printf("Table it detected  : %s\n", $response->getTableRange());
printf("Where it wrote     : %s\n", $response->getUpdates()->getUpdatedRange());
printf("Rows added         : %d\n", $response->getUpdates()->getUpdatedRows());
printf("Cells written      : %d\n\n", $response->getUpdates()->getUpdatedCells());

// Read the sheet back so the result is the sheet, not the response.
$rows = $service->spreadsheets_values->get($spreadsheetId, 'Sheet1!A1:D12')->getValues() ?? [];

echo "Sheet1 after the append:\n";
foreach ($rows as $i => $row) {
    printf("  row %-2d %s\n", $i + 1, implode(' | ', $row));
}

The full script from Append Google Sheets Rows Using Google Sheets API PHP Client — copy, run, adapt.

IOFactory::load() PhpSpreadsheet
Open any spreadsheet file
getActiveSheet() PhpSpreadsheet
Select the worksheet to fill
fromArray() PhpSpreadsheet
Write many rows at once
getCalculatedValue() PhpSpreadsheet
Read a formula result
save('php://output') PhpSpreadsheet
Stream the file as a download
spreadsheets_values->get() Google Sheets
Read a range of cells
spreadsheets_values->update() Google Sheets
Write a range of cells
spreadsheets->create() Google Sheets
Create a new spreadsheet
json_encode() PHP
Serialize rows to JSON
header() PHP
Send the download headers