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.

format-cells.php View article
<?php

require 'vendor/autoload.php';

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

$spreadsheetId = 'YOUR_SPREADSHEET_ID';
$keyFile = 'service-account.json';
$tabName = 'Sales';

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

$service = new Sheets($client);

/**
 * Return the numeric sheetId for a tab name, creating the tab if needed.
 */
function sheetIdFor(Sheets $service, string $spreadsheetId, string $title): int
{
    foreach ($service->spreadsheets->get($spreadsheetId)->getSheets() as $sheet) {
        if ($sheet->getProperties()->getTitle() === $title) {
            return $sheet->getProperties()->getSheetId();
        }
    }

    $service->spreadsheets->batchUpdate($spreadsheetId, new BatchUpdateSpreadsheetRequest([
        'requests' => [
            new Request(['addSheet' => ['properties' => ['title' => $title]]]),
        ],
    ]));

    return sheetIdFor($service, $spreadsheetId, $title);
}

$sheetId = sheetIdFor($service, $spreadsheetId, $tabName);

$service->spreadsheets_values->update(
    $spreadsheetId,
    $tabName . '!A1',
    new ValueRange(['values' => [
        ['Item', 'Qty', 'Price'],
        ['Widget', 120, 9.99],
        ['Gadget', 45, 24.50],
        ['Doohick', 300, 1.75],
    ]]),
    ['valueInputOption' => 'USER_ENTERED']
);

$headerFormat = new Request(['repeatCell' => [
    'range' => [
        'sheetId'          => $sheetId,
        'startRowIndex'    => 0,
        'endRowIndex'      => 1,
        'startColumnIndex' => 0,
        'endColumnIndex'   => 3,
    ],
    'cell' => ['userEnteredFormat' => [
        'backgroundColor'     => ['red' => 0.20, 'green' => 0.36, 'blue' => 0.00],
        'horizontalAlignment' => 'CENTER',
        'textFormat'          => [
            'bold'            => true,
            'fontSize'        => 12,
            'foregroundColor' => ['red' => 1.0, 'green' => 1.0, 'blue' => 1.0],
        ],
    ]],
    'fields' => 'userEnteredFormat(backgroundColor,horizontalAlignment,textFormat)',
]]);

$priceFormat = new Request(['repeatCell' => [
    'range' => [
        'sheetId'          => $sheetId,
        'startRowIndex'    => 1,
        'endRowIndex'      => 4,
        'startColumnIndex' => 2,
        'endColumnIndex'   => 3,
    ],
    'cell' => ['userEnteredFormat' => [
        'numberFormat' => ['type' => 'CURRENCY', 'pattern' => '"$"#,##0.00'],
    ]],
    'fields' => 'userEnteredFormat.numberFormat',
]]);

$service->spreadsheets->batchUpdate($spreadsheetId, new BatchUpdateSpreadsheetRequest([
    'requests' => [$headerFormat, $priceFormat],
]));

echo "Formatting applied.\n\n";

$meta = $service->spreadsheets->get($spreadsheetId, [
    'ranges'          => [$tabName . '!A1'],
    'includeGridData' => true,
    'fields'          => 'sheets(data(rowData(values(userEnteredFormat))))',
]);

$format = $meta->getSheets()[0]->getData()[0]->getRowData()[0]->getValues()[0]->getUserEnteredFormat();
$text = $format->getTextFormat();
$fill = $format->getBackgroundColor();

echo "A1 as the spreadsheet now stores it:\n";
printf("  bold       : %s\n", $text->getBold() ? 'yes' : 'no');
printf("  font size  : %s\n", $text->getFontSize());
printf("  text colour: %.2f / %.2f / %.2f\n",
    $text->getForegroundColor()->getRed() ?? 0,
    $text->getForegroundColor()->getGreen() ?? 0,
    $text->getForegroundColor()->getBlue() ?? 0);
printf("  fill colour: %.2f / %.2f / %.2f\n",
    $fill->getRed() ?? 0, $fill->getGreen() ?? 0, $fill->getBlue() ?? 0);
printf("  alignment  : %s\n", $format->getHorizontalAlignment());

$prices = $service->spreadsheets_values->get($spreadsheetId, $tabName . '!C2:C4', [
    'valueRenderOption' => 'FORMATTED_VALUE',
])->getValues();

echo "\nPrice column as displayed:\n";
foreach ($prices as $row) {
    printf("  %s\n", $row[0]);
}

The full script from Format Google Sheets Cells 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