google docs api php
PHP Quickstart
Complete the steps described in the rest of this page to create a simple PHP command-line application that makes requests to the Google Sheets API.
Prerequisites
To run this quickstart, you need the following prerequisites:
Step 1: Install the Google Client Library
See the library’s installation page for the alternative installation options.
Step 2: Set up the sample
Create a file named quickstart.php in your working directory and copy in the following code:
Step 3: Run the sample
Run the sample using the following command:
The first time you run the sample, it prompts you to authorize access:
Browse to the provided URL in your web browser.
If you are not already signed in to your Google account, you are be prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for the authorization.
Notes
Troubleshooting
This section describes some common issues that you may encounter while attempting to run this quickstart and suggests possible solutions.
SSL certificate problem: unable to get local issuer certificate
This error indicates that the underlying HTTP libraries can’t find a certificate store, and are therefore unable to setup the SSL connection to Google’s servers. See the Guzzle library’s documentation for information on how to setup a certificate store on your machine.
Uncaught InvalidArgumentException: missing the required redirect URI
This error occurs when the credentials.json file used contains a client ID of the wrong type. This code requires an OAuth client ID of type Other, which will be created for you when using the button in Step 1. If creating your own client ID please ensure you select the correct type.
This app isn’t verified
If the OAuth consent screen displays the warning «This app isn’t verified,» your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to
Further reading
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
PHP Quickstart
Complete the steps described in the rest of this page to create a simple PHP command-line application that makes requests to the Google Docs API.
Prerequisites
To run this quickstart, you need the following prerequisites:
Step 1: Install the Google Client Library
See the library’s installation page for the alternative installation options.
Step 2: Set up the sample
Create a file named quickstart.php in your working directory and copy in the following code:
Step 3: Run the sample
Run the sample using the following command:
The first time you run the sample, it prompts you to authorize access:
Browse to the provided URL in your web browser.
If you are not already signed in to your Google account, you are be prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for the authorization.
Notes
Troubleshooting
This section describes some common issues that you may encounter while attempting to run this quickstart and suggests possible solutions.
SSL certificate problem: unable to get local issuer certificate
This error indicates that the underlying HTTP libraries can’t find a certificate store, and are therefore unable to setup the SSL connection to Google’s servers. See the Guzzle library’s documentation for information on how to setup a certificate store on your machine.
Uncaught InvalidArgumentException: missing the required redirect URI
This error occurs when the credentials.json file used contains a client ID of the wrong type. This code requires an OAuth client ID of type Other, which will be created for you when using the button in Step 1. If creating your own client ID please ensure you select the correct type.
This app isn’t verified
If the OAuth consent screen displays the warning «This app isn’t verified,» your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to
Further reading
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Google Sheets API Overview
The Google Sheets API is a RESTful interface that lets you read and modify a spreadsheet’s data. The most common uses of this API include the following tasks:
Below is a list of common terms used in the Sheets API:
The primary object in Google Sheets that can contain multiple sheets, each with structured information contained in cells. Every spreadsheet is represented by a Spreadsheet resource and has a unique spreadsheetId value, containing letters, numbers, hyphens, or underscores. You can find the spreadsheet ID in a Google Sheets URL:
https://docs.google.com/spreadsheets/d/ spreadsheetId /edit#gid=0
A page or tab within a spreadsheet. Each sheet is represented by a Sheet resource and has a unique title and numeric sheetId value. You can find the sheet ID in a Google Sheets URL:
An individual field of text or data within a sheet. Cells are arranged in rows and columns, and can be grouped together as a range of cells. Each cell is represented by a CellData resource, but doesn’t have a unique ID value. Instead, cells are identified by their row and column coordinates.
A syntax used to define a cell or range of cells with a string that contains the sheet name and starting and ending cell coordinates using column letters and row numbers. This method is most common and useful when referencing an absolute range of cells.
Show examples
A syntax used to define a cell or range of cells with a string that contains the sheet name and starting and ending cell coordinates using row numbers and column numbers. This method is less common, but can be useful when referencing a range of cells relative to a given cell’s position.
Show examples
A defined cell or range of cells with a custom name to simplify references throughout an application. A named range is represented by a FilterView resource.
A defined cell or range of cells that cannot be modified. A protected range is represented by a ProtectedRange resource.
Next steps
To get started with the Google Sheets API:
To learn about developing with Google Workspace APIs, including handling authentication and authorization, refer to Get started as a Workspace developer.
To learn how to configure and run a simple Sheets API app, read the Quickstarts overview.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[Примеры] Google Sheets/Таблицы API PHP
Содержание:
codd.mail@gmail.com или в telegram alex_codd
1. Подготовительный этап
1. Создаём сервисный аккаунт и получаем ключ доступа к API.
2. Открываем доступ к таблице для email адреса сервисного аккаунта:
Email адрес сервисного аккаунта можно узнать на странице вашего проекта в Google Developers Console:
3. Устанавливаем библиотеку для работы с Google APIs: Google APIs Client Library for PHP.
Для установки с помощью Composer выполните в консоли следующие команды:
После установки подключаем файл AutoLoader:
4. Ключ сервисного аккаунта, созданный на первом шаге, кладём в папку с нашим проектом.
2. Приступаем к работе с API Google Sheets
spreadsheetId — ID таблицы (example blog)
sheetId — ID листа (Лист 1, Лист 2, …)
Генерируем красивую Google-таблицу из своей программы (используя Google Sheets API v4)
Постановка задачи
Пусть нам нужно создать программой на языке Python вот такую таблицу:
Особенности этой таблицы:
Решение
Сразу отметаем неподходящие библиотеки. Например, gspread. Это обёртка над Google Sheets API v3, в котором нет методов для настройки оформления таблицы. Даже ширину столбца задать не получится.
Шаг 1. Создать сервисный аккаунт
Шаг 2. Установить необходимые библиотеки
А именно, google-api-python-client. Установить можно при помощи pip, например:
Эта библиотека притянет необходимые зависимости (такие, как oauth2client и прочие).
Шаг 3. Кодить
3.1. Service-объект
Создаём Service-объект, для работы с Google-таблицами:
3.2. Термины и id’шники
Теперь на секунду приостановимся и обсудим терминологию.
3.3. Новый spreadsheet
В ответ получаем снова объект Spreadsheet, только заполненных параметров больше:
Можно было задать многие из них в запросе, но для решения текущей задачи нас устраивают параметры по умолчанию.
Параметру locale было задано значение ru_RU не случайно, но об этом позже.
Что же делать? Ответ очевиден: выдать доступ к документу тоже с помощью API.
Можно создать документ вручную на своём Google-диске и дать доступ сервисному аккаунту (то есть вручную выдать разрешения тому e-mail наподобие account@test-proj-for-habr-article.iam.gserviceaccount.com). Затем работать с этим документом через API.
Меня этот вариант не устроил, потому что мне требовалось научить программу создавать много разных документов.
3.4. Доступ к новому документу
У нашего объекта service нет метода для настройки доступа к документу. Его просто нет в Google Sheets API. Зато он есть в Google Drive API v3. Пишем код.
Такой код даёт доступ всем на чтение по ссылке. Допустим, мы желаем вместо этого дать доступ на редактирование пользователю user@example.com. Для этого вместо
3.5. Ещё немного теории
Есть функция spreadsheets.batchUpdate. Она применяет сразу пачку изменений к документу. А точнее, сначала она проверяет всю пачку на корректность. Если всё OK, то атомарно применяет всё и возвращает соответствующую пачку результатов. Список изменений, которые можно применять этой функцией, находится здесь.
3.6. Ширина столбцов
Чтобы задать ширину столбцов нужно сделать UpdateDimensionPropertiesRequest.
Получилось весьма громоздко и много копипасты. На этом этапе я решил написать небольшой класс-обёртку над Sheets API, который даст мне в удобном виде необходимые методы.
3.7. Логика класса-обёртки
Пусть класс-обёртка (назовём его Spreadsheet) хранит список requests и в своём методе runPrepared передаст его функции spreadsheets.batchUpdate, а затем очистит. Добавлять элементы в этот список будут методы вида prepare_соответствующийЗапрос.
Теперь код для задания ширины столбцов выглядит так:
И вот код методов prepare_setColumnWidth и prepare_setColumnsWidth:
Код метода runPrepared я приведу немного далее, потому что он пополнится ещё кое-чем.
3.8. Заполнение ячеек данными
Для заполнения ячеек информацией в Google Sheets API v4 предусмотрена функция spreadsheets.values.batchUpdate, работающая по тому же принципу, что и spreadsheets.batchUpdate. Она принимает список прямоугольников и значений, которые нужно записать в каждый из них. Кроме этого, принимает параметр ValueInputOption:
Вот так можно заполнить данными пару прямоугольников на листе без использования нашего класса-обёртки:
Теперь сделаем, чтобы наш класс-обёртка предоставил удобные методы для достижения того же результата.
Пусть функция spreadsheets.values.batchUpdate вызывается в методе runPrepared, а метод prepare_setValues добавляет прямоугольник и данные в список valueRanges, который при вызове runPrepared будет передан в spreadsheets.values.batchUpdate.
Код методов prepare_setValues и runPrepared:
Заполним данными ту же пару прямоугольников, что и в примере выше, но уже с использованием нашего класса-обёртки:
3.9. Объединение ячеек, настройка жирности, формата отображения, цвета фона и прочего
Кому не терпится, можете сразу читать полный код класса Spreadsheet и пример его использования, который является решением задачи, поставленной в начале статьи.
Для более терпеливого читателя:
Некоторые тонкости
Q3: В запросах, передаваемых функции spreadsheets.batchUpdate, параметр range имеет формат GridRange:
А в прямоугольниках с данными для функции spreadsheets.values.batchUpdate параметр range — это строка, вида Название_листа!A5:E7 (A1 notation). Странно.
A3: Да. Возможно, в комментариях к статье кто-нибудь объяснит, почему так.
В классе-обёртке я сделал для удобства метод toGridRange.
Q4: Пикачу, который в таблице в начале статьи, посажен туда программно?
A4: Нет, Пикачу я разместил в таблице вручную. Не уверен, что Google Sheets API v4 позволяет сделать это программно, сходу нужную функцию не нашёл.
Q5: Есть ли какие-то ограничения использования Google Sheets API v4?
A5: Да, они называются квотами. За ними можно следить в Google Developers Console. Там же можно отправить запрос на увеличение квоты, если будет не хватать.
Заключение
Если Вы дочитали досюда, то, вероятно, освоили, как программно создать spreadsheet, и теперь горите желанием использовать Google-таблицы во всех своих проектах 🙂