SpreadSheet-Coding.com

Google Sheets

This section is about driving Google Sheets from PHP — a spreadsheet that lives in Google Drive and is edited over an API, rather than a file you open, change and save. The unit of work is a request against a spreadsheet ID, not a file handle.

Set up access first

Nothing else works until Google trusts your code. This is the part that trips people up, and it is worth doing in order:

For anything running unattended — a cron job, a queue worker, an export endpoint — the service account is the one to use. It belongs to your code rather than to a person, so there is no consent screen and no token to refresh by hand; you share the spreadsheet with its email address like you would with a colleague. The older OAuth walkthrough is still here for the interactive case, but start with the service account.

Reading and writing values

The everyday work, and the closest thing this API has to a core loop:

Changing how the sheet looks

Formatting goes through a different, batched part of the API than values do — a list of requests applied in one call rather than a write to a range. Borders, merged cells, the spreadsheet title and duplicating a sheet all follow that same shape, so the first one you learn carries over.

Working with Excel files instead?

If the spreadsheet is a file on disk or an upload rather than a document in Drive, you want PhpSpreadsheet — reading and writing .xlsx from PHP is on the Excel side. Moving between the two is a normal thing to want, and the conversion articles cover it.

Browse every Google Sheets API article