{"id":19651731,"url":"https://github.com/tanaikech/go-gdoctableapp","last_synced_at":"2025-07-06T21:34:32.012Z","repository":{"id":57514804,"uuid":"197485124","full_name":"tanaikech/go-gdoctableapp","owner":"tanaikech","description":"This is a Golang library for managing tables on Google Document using Google Docs API.","archived":false,"fork":false,"pushed_at":"2023-04-18T05:20:56.000Z","size":138,"stargazers_count":10,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-06-21T19:58:38.811Z","etag":null,"topics":["developer-tools","golang","golang-library","google-docs","google-docs-api","library","manager","table"],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tanaikech.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-07-18T01:00:24.000Z","updated_at":"2024-06-20T15:57:34.000Z","dependencies_parsed_at":"2024-06-21T19:06:00.301Z","dependency_job_id":"bedaa741-a3e4-448b-b9c7-4e20fa7b4d1a","html_url":"https://github.com/tanaikech/go-gdoctableapp","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tanaikech%2Fgo-gdoctableapp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tanaikech%2Fgo-gdoctableapp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tanaikech%2Fgo-gdoctableapp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tanaikech%2Fgo-gdoctableapp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tanaikech","download_url":"https://codeload.github.com/tanaikech/go-gdoctableapp/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224124894,"owners_count":17259746,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["developer-tools","golang","golang-library","google-docs","google-docs-api","library","manager","table"],"created_at":"2024-11-11T15:07:44.087Z","updated_at":"2024-11-11T15:07:45.033Z","avatar_url":"https://github.com/tanaikech.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# go-gdoctableapp\r\n\r\n[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENCE)\r\n\r\n\u003ca name=\"top\"\u003e\u003c/a\u003e\r\n\r\n# Overview\r\n\r\nThis is a Golang library for managing tables on Google Document using Google Docs API.\r\n\r\n# Description\r\n\r\nGoogle Docs API has been released. When I used this API, I found that it is very difficult for me to manage the tables on Google Document using Google Docs API. Although I checked [the official document](https://developers.google.com/docs/api/how-tos/tables), unfortunately, I thought that it's very difficult for me. So in order to easily manage the tables on Google Document, I created this library.\r\n\r\n## Features\r\n\r\n- All values can be retrieved from the table on Google Document.\r\n- Values can be put to the table.\r\n- Delete table, rows and columns of the table.\r\n- New table can be created by including values.\r\n- Append rows to the table by including values.\r\n- Replace texts with images.\r\n\t- The image data can be retrieved from URL.\r\n\t- The image data can be uploaded from the local PC.\r\n\r\n## Languages\r\n\r\nI manages the tables on Google Document using several languages. So I created the libraries for 4 languages which are golang, node.js and python. Google Apps Script has Class DocumentApp. So I has never created the GAS library yet.\r\n\r\n- [go-gdoctableapp](https://github.com/tanaikech/go-gdoctableapp)\r\n\t- This library uses [google-api-go-client](https://github.com/googleapis/google-api-go-client).\r\n- [node-gdoctableapp](https://github.com/tanaikech/node-gdoctableapp)\r\n- [gdoctableapppy](https://github.com/tanaikech/gdoctableapppy)\r\n- [google-docs-table-factory](https://github.com/gumatias/google-docs-table-factory) by gumatias\r\n\r\n# Method\r\n\r\n| Method                                                                       | Explanation                                       |\r\n| :--------------------------------------------------------------------------- | :------------------------------------------------ |\r\n| [`GetTables()`](#gettables)                                                  | Get all tables from Document.                     |\r\n| [`GetValues()`](#getvalues)                                                  | Get values from a table from Document.            |\r\n| [`SetValuesBy2DArray(values [][]interface{})`](#setvaluesby2darray)          | Set values to a table with 2 dimensional array.   |\r\n| [`SetValuesByObject(values []ValueObject)`](#setbaluesbyobject)              | Set values to a table with an object.             |\r\n| [`DeleteTable()`](#deletetable)                                              | Delete a table.                                   |\r\n| [`DeleteRowsAndColumns(d *DeleteRowsColumnsRequest)`](#deleterowsandcolumns) | Delete rows and columns of a table.               |\r\n| [`CreateTable(c *CreateTableRequest)`](#createtable)                         | Create new table including sell values.           |\r\n| [`AppendRow(c *AppendRowRequest)`](#appendrow)                               | Append row to a table by including values.        |\r\n| [`ReplaceTextsToImagesByURL(from, to string)`](#replacetexts)                | Replace texts with images from URL.               |\r\n| [`ReplaceTextsToImagesByFile(from, to string)`](#replacetexts)               | Replace texts with images from files on local PC. |\r\n\r\nThis library uses [google-api-go-client](https://github.com/googleapis/google-api-go-client).\r\n\r\n## Responses\r\n\r\nThe structure of response from this library is as follows.\r\n\r\n```golang\r\nResult struct {\r\n\tTables           []Table       `json:\"tables,omitempty\"`\r\n\tValues           [][]string    `json:\"values,omitempty\"`\r\n\tResponseFromAPIs []interface{} `json:\"responseFromAPIs,omitempty\"`\r\n\tLibraryVersion   string        `json:\"libraryVersion\"`\r\n}\r\n```\r\n\r\n- When `GetTables()` is used, you can see the values with `Tables`.\r\n- When `GetValues()` is used, you can see the values with `Values`.\r\n- When other methods are used and the option of `ShowAPIResponse` is `true`, you can see the responses from APIs which were used for the method. And also, you can know the number of APIs, which were used for the method, by the length of array of `ResponseFromAPIs`.\r\n\r\n# Usage\r\n\r\nAbout the authorization, please check the section of [Authorization](#authorization). In order to use this library, it is required to confirm that [the Quickstart](https://developers.google.com/docs/api/quickstart/go) works fine.\r\n\r\nPlease import this libray as follows.\r\n\r\n```go\r\ngdoctableapp \"github.com/tanaikech/go-gdoctableapp\"\r\n```\r\n\r\nAnd, please use as follows.\r\n\r\n```go\r\nclient := ### // Please use your client.\r\ng := gdoctableapp.New()\r\n\r\nres, err := g.Docs(documentID).TableIndex(tableIndex).GetValues().Do(client)\r\n```\r\n\r\n- You can see the sample script including the authorization script at [here](#authorization)\r\n\r\n## Scope\r\n\r\nIn this library, using the scope of `https://www.googleapis.com/auth/documents` is recommended. When the method of `ReplaceTextsToImagesByFile` is used, also please add `https://www.googleapis.com/auth/drive`.\r\n\r\n\u003ca name=\"gettables\"\u003e\u003c/a\u003e\r\n\r\n## 1. GetTables\r\n\r\nGet all tables from Document. All values, table index and table position are retrieved.\r\n\r\n### Sample script\r\n\r\nThis sample script retrieves all tables from the Google Document of document ID.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ng := gdoctableapp.New()\r\nres, err := g.Docs(documentID).GetTables().Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res.Tables) // You can see the retrieved values like this.\r\n```\r\n\r\nthe structure of `res.Tables` is as follows.\r\n\r\n```golang\r\nTable struct {\r\n\tIndex         int64      `json:\"index\"` // TableIdx\r\n\tValues        [][]string `json:\"values\"`\r\n\tTablePosition struct {\r\n\t\tStartIndex int64 `json:\"startIndex\"`\r\n\t\tEndIndex   int64 `json:\"endIndex\"`\r\n\t}\r\n}\r\n```\r\n\r\nWhen the option of `ShowAPIResponse` is used, the responses from Docs API can be retrieved. **This option can be used for all methods.**\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ng := gdoctableapp.New()\r\nres, err := g.Docs(documentID).GetTables().ShowAPIResponse(true).Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res.Tables)           // You can see the retrieved values like this.\r\nfmt.Println(res.ResponseFromAPIs) // You can see the responses from Docs API like this.\r\n```\r\n\r\n\u003ca name=\"getvalues\"\u003e\u003c/a\u003e\r\n\r\n## 2. GetValues\r\n\r\nGet values from the table. All values are retrieved.\r\n\r\n### Sample script\r\n\r\nThis sample script retrieves the values from 1st table in Google Document. You can see the retrieved values as `[][]string`. Because when the values are retrieved by Docs API, all values are automatically converted to the string data.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ntableIndex := 0\r\ng := gdoctableapp.New()\r\nres, err := g.Docs(documentID).TableIndex(tableIndex).GetValues().Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res.Values) // You can see the retrieved values like this.\r\n```\r\n\r\n- `documentID`: Document ID.\r\n- `tableIndex`: Table index. If you want to use the 3rd table in Google Document. It's 2. The start number of index is 0.\r\n- `client`: `*Client` for using Docs API. Please check the section of [Authorization](#authorization).\r\n\r\n\u003ca name=\"setvaluesby2darray\"\u003e\u003c/a\u003e\r\n\r\n## 3. SetValuesBy2DArray\r\n\r\nSet values to the table with 2 dimensional array. When the rows and columns of values which are put are over those of the table, this method can automatically expand the rows and columns.\r\n\r\n### Sample script\r\n\r\nThis sample script puts the values to the first table in Google Document.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ntableIndex := 0\r\ng := gdoctableapp.New()\r\nvaluesBy2DArray := [][]interface{}{{\"a1\", \"b1\"}, {\"a2\", \"b2\"}, {\"a3\", \"b3\", \"c3\"}}\r\nres, err := g.Docs(documentID).TableIndex(tableIndex).SetValuesBy2DArray(valuesBy2DArray).Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res)\r\n```\r\n\r\n- `documentID`: Document ID.\r\n- `tableIndex`: Table index. If you want to use the 3rd table in Google Document. It's 2. The start number of index is 0.\r\n- `client`: `*Client` for using Docs API. Please check the section of [Authorization](#authorization).\r\n- `valuesBy2DArray`: `[][]interface{}`\r\n\r\n### Result\r\n\r\nWhen above script is run, the following result is obtained.\r\n\r\n#### From:\r\n\r\n![](images/fig1.png)\r\n\r\n#### To:\r\n\r\n![](images/fig2.png)\r\n\r\n\u003ca name=\"setbaluesbyobject\"\u003e\u003c/a\u003e\r\n\r\n## 4. SetValuesByObject\r\n\r\nSet values to a table with an object. In this method, you can set the values using the range. When the rows and columns of values which are put are over those of the table, this method can automatically expand the rows and columns.\r\n\r\n### Sample script\r\n\r\nThis script puts the values with the range to the first table in Google Document.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ntableIndex := 0\r\ng := gdoctableapp.New()\r\n\r\nvaluesByObject := []gdoctableapp.ValueObject{}\r\n\r\nvo1 := \u0026gdoctableapp.ValueObject{}\r\nvo1.Range.StartRowIndex = 0\r\nvo1.Range.StartColumnIndex = 0\r\nvo1.Values = [][]interface{}{{\"A1\"}, {\"A2\", \"B2\", \"c2\", \"d2\"}, {\"A3\"}}\r\nvaluesByObject = append(valuesByObject, *vo1)\r\n\r\nvo2 := \u0026gdoctableapp.ValueObject{}\r\nvo2.Range.StartRowIndex = 0\r\nvo2.Range.StartColumnIndex = 1\r\nvo2.Values = [][]interface{}{{\"B1\", \"C1\"}}\r\nvaluesByObject = append(valuesByObject, *vo2)\r\n\r\nres, err := g.Docs(documentID).TableIndex(tableIndex).SetValuesByObject(valuesByObject).Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res)\r\n```\r\n\r\n- `documentID`: Document ID.\r\n- `tableIndex`: Table index. If you want to use the 3rd table in Google Document. It's 2. The start number of index is 0.\r\n- `client`: `*Client` for using Docs API. Please check the section of [Authorization](#authorization).\r\n- `Range.StartRowIndex` of `valuesByObject`: Row index of `values[0][0]`.\r\n- `Range.StartColumnIndex` of `valuesByObject`: Column index of `values[0][0]`.\r\n- `Values` of `valuesByObject`: Values you want to put.\r\n\r\nFor example, when the row, column indexes and values are 1, 2 and \"value\", respectively, \"value\" is put to \"C3\".\r\n\r\n### Result\r\n\r\nWhen above script is run, the following result is obtained.\r\n\r\n#### From:\r\n\r\n![](images/fig1.png)\r\n\r\n#### To:\r\n\r\n![](images/fig3.png)\r\n\r\n\u003ca name=\"deleteuable\"\u003e\u003c/a\u003e\r\n\r\n## 5. DeleteTable\r\n\r\n### Sample script\r\n\r\nThis script deletes the first table in Google Document.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ntableIndex := 0\r\ng := gdoctableapp.New()\r\n\r\nres, err := g.Docs(documentID).TableIndex(tableIndex).DeleteTable().Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res)\r\n```\r\n\r\n- `documentID`: Document ID.\r\n- `tableIndex`: Table index. If you want to use the 3rd table in Google Document. It's 2. The start number of index is 0.\r\n- `client`: `*Client` for using Docs API. Please check the section of [Authorization](#authorization).\r\n\r\n\u003ca name=\"deleterowsandcolumns\"\u003e\u003c/a\u003e\r\n\r\n## 6. DeleteRowsAndColumns\r\n\r\n### Sample script\r\n\r\nThis script deletes rows of indexes of 3, 1 and 2 of the first table in Google Document. And also this script deletes columns of indexes of 2, 1 and 3.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ntableIndex := 0\r\ng := gdoctableapp.New()\r\n\r\nobj := \u0026gdoctableapp.DeleteRowsColumnsRequest{\r\n\tRows:    []int64{3, 1, 2}, // Start index is 0.\r\n\tColumns: []int64{2, 1, 3}, // Start index is 0.\r\n}\r\nres, err := g.Docs(documentID).TableIndex(tableIndex).DeleteRowsAndColumns(obj).Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res)\r\n```\r\n\r\n- `documentID`: Document ID.\r\n- `tableIndex`: Table index. If you want to use the 3rd table in Google Document. It's 2. The start number of index is 0.\r\n- `client`: `*Client` for using Docs API. Please check the section of [Authorization](#authorization).\r\n- `Rows` of `obj`: Indexes of rows you want to delete.\r\n- `Columns` of `obj`: Indexes of columns you want to delete.\r\n\r\n\u003ca name=\"createtable\"\u003e\u003c/a\u003e\r\n\r\n## 7. CreateTable\r\n\r\n### Sample script\r\n\r\nThis script creates new table to the top of Google Document, and the cells of the table have values.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ng := gdoctableapp.New()\r\n\r\nobj := \u0026gdoctableapp.CreateTableRequest{\r\n\tRows:    3,\r\n\tColumns: 5,\r\n\tIndex:   1,\r\n\t// Append:  true, // When this is used instead of \"Index\", new table is created to the end of Document.\r\n\tValues: [][]interface{}{{\"a1\", \"b1\"}, {\"a2\", \"b2\"}, {\"a3\", \"b3\", \"c3\"}},\r\n}\r\nres, err := g.Docs(documentID).CreateTable(obj).Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res)\r\n```\r\n\r\n- `documentID`: Document ID.\r\n- `client`: `*Client` for using Docs API. Please check the section of [Authorization](#authorization).\r\n- `Rows` of `obj`: Number of rows of new table.\r\n- `Columns` of `obj`: Number of columns of new table.\r\n- `Index` of `obj`: Index of Document for putting new table. For example, `1` is the top of Document.\r\n- `Append` of `obj`: When `Append` is `true` instead of `Index`, the new table is created to the end of Google Document.\r\n- `Values` of `obj`: If you want to put the values when new table is created, please use this.\r\n\r\n### Result\r\n\r\nWhen above script is run, the following result is obtained. In this case, the new table is created to the top of Google Document.\r\n\r\n![](images/fig4.png)\r\n\r\n\u003ca name=\"appendrow\"\u003e\u003c/a\u003e\r\n\r\n## 8. AppendRow\r\n\r\n### Sample script\r\n\r\nThis sample script appends the values to the first table of Google Document.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\ntableIndex := 0\r\ng := gdoctableapp.New()\r\n\r\nobj := \u0026gdoctableapp.AppendRowRequest{\r\n\tValues: [][]interface{}{{\"a1\", \"b1\", \"c1\", 1, \"\", 2}, {\"a2\", \"b2\", \"c2\", 1, \"\", 2}},\r\n}\r\nres, err := g.Docs(documentID).TableIndex(tableIndex).AppendRow(obj).Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res)\r\n```\r\n\r\n- `documentID`: Document ID.\r\n- `tableIndex`: Table index. If you want to use the 3rd table in Google Document. It's 2. The start number of index is 0.\r\n- `client`: `*Client` for using Docs API. Please check the section of [Authorization](#authorization).\r\n- `Values` of `obj`: Values you want to append to the existing table.\r\n\r\n### Result\r\n\r\nWhen above script is run, the following result is obtained. In this case, the values are put to the last row. And you can see that 3 columns are automatically added when the script is run.\r\n\r\n#### From:\r\n\r\n![](images/fig5.png)\r\n\r\n#### To:\r\n\r\n![](images/fig6.png)\r\n\r\n\u003ca name=\"replacetexts\"\u003e\u003c/a\u003e\r\n\r\n## 9. ReplaceTextsToImagesByURL and ReplaceTextsToImagesByFile\r\n\r\n### Sample script 1\r\n\r\nIn this sample, the texts `{{sample}}` in all tables are replaced with the image retrieved by **the URL of `https://###/sample.png`**.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\nsearchText := \"{{sample}}\"\r\ntableOnly := true\r\nreplaceImageURL := \"https://###/sample.png\"\r\ng := gdoctableapp.New()\r\n\r\nres, err := g.Docs(documentID).ReplaceTextsToImagesByURL(searchText, replaceImageURL).TableOnly(tableOnly).Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res)\r\n```\r\n\r\n### Sample script 2\r\n\r\nIn this sample, the texts `{{sample}}` in all tables are replaced with the image retrieved by **the file of `./sample.png` on your local PC**.\r\n\r\n```golang\r\ndocumentID := \"###\"\r\nsearchText := \"{{sample}}\"\r\ntableOnly := true // default is false\r\nreplaceImageFilePath := \"./sample.png\"\r\ng := gdoctableapp.New()\r\n\r\nres, err := g.Docs(documentID).ReplaceTextsToImagesByFile(searchText, replaceImageFilePath).TableOnly(tableOnly).Do(client)\r\nif err != nil {\r\n\tfmt.Println(err)\r\n\tos.Exit(1)\r\n}\r\nfmt.Println(res)\r\n```\r\n\r\n- `documentID`: Document ID.\r\n- `client`: `*Client` for using Docs API. Please check the section of [Authorization](#authorization).\r\n- `searchText`: Search text. This text is replaced with image.\r\n- `tableOnly`: When this is `true`, only texts in the table are replaced with image. When this is `false`, the texts in the body are replaced.\r\n- `replaceImageURL`: URL of the image.\r\n- `replaceImageFilePath`: File path of the image.\r\n\r\nIf you want to change the width and height of the image, please use the method of `SetImageSize(width, height float64)` like below.\r\n\r\n```golang\r\nres, err := g.Docs(documentID).SetImageSize(100, 100).ReplaceTextsToImagesByFile(searchText, replaceImageFilePath).TableOnly(tableOnly).Do(client)\r\n```\r\n\r\n### Note\r\n\r\n- The flow for replacing the text with the image on the local PC.\r\n\r\n  1. Upload the image from local PC to Google Drive.\r\n  2. Publicly share the image file. - The time for sharing is several seconds. The file is delete after the image is put.\r\n  3. Put the image using the URL of the publicly shared file.\r\n  4. Delete the image. - Even when the image is delete from Google Drive, the put image on Google Document is not deleted.\r\n\r\n- About `SetImageSize`\r\n  \u003e [**objectSize**](https://developers.google.com/docs/api/reference/rest/v1/documents/request#insertinlineimagerequest): The size that the image should appear as in the document. This property is optional and the final size of the image in the document is determined by the following rules: _ If neither width nor height is specified, then a default size of the image is calculated based on its resolution. _ If one dimension is specified then the other dimension is calculated to preserve the aspect ratio of the image. \\* If both width and height are specified, the image is scaled to fit within the provided dimensions while maintaining its aspect ratio.\r\n\r\n### Result\r\n\r\nWhen above script is run, the following result is obtained.\r\n\r\n#### From:\r\n\r\n![](images/fig7.png)\r\n\r\n#### To:\r\n\r\n![](images/fig8.png)\r\n\r\nThe image of `https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png` was used as the sample image.\r\n\r\nWhen `tableOnly` is `false`, the following result is retrieved.\r\n\r\n![](images/fig9.png)\r\n\r\n\u003ca name=\"authorization\"\u003e\u003c/a\u003e\r\n\r\n# Authorization\r\n\r\nThere are 2 patterns for using this library.\r\n\r\n## 1. Use OAuth2\r\n\r\nDocument of OAuth2 is [here](https://developers.google.com/identity/protocols/OAuth2).\r\n\r\n### Sample script\r\n\r\nIn this sample script, the authorization process uses [the Quickstart for Go](https://developers.google.com/docs/api/quickstart/go). You can see the detail information at there.\r\n\r\n```golang\r\npackage main\r\n\r\nimport (\r\n\t\"context\"\r\n\t\"encoding/json\"\r\n\t\"fmt\"\r\n\t\"log\"\r\n\t\"net/http\"\r\n\t\"os\"\r\n\r\n\tgdoctableapp \"github.com/tanaikech/go-gdoctableapp\"\r\n\t\"golang.org/x/oauth2\"\r\n\t\"golang.org/x/oauth2/google\"\r\n\t\"google.golang.org/api/docs/v1\"\r\n)\r\n\r\n// Retrieves a token, saves the token, then returns the generated client.\r\nfunc getClient(config *oauth2.Config) *http.Client {\r\n\ttokFile := \"token.json\"\r\n\ttok, err := tokenFromFile(tokFile)\r\n\tif err != nil {\r\n\t\ttok = getTokenFromWeb(config)\r\n\t\tsaveToken(tokFile, tok)\r\n\t}\r\n\treturn config.Client(context.Background(), tok)\r\n}\r\n\r\n// Requests a token from the web, then returns the retrieved token.\r\nfunc getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\r\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\r\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\r\n\t\t\"authorization code: \\n%v\\n\", authURL)\r\n\r\n\tvar authCode string\r\n\tif _, err := fmt.Scan(\u0026authCode); err != nil {\r\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\r\n\t}\r\n\r\n\ttok, err := config.Exchange(oauth2.NoContext, authCode)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\r\n\t}\r\n\treturn tok\r\n}\r\n\r\n// Retrieves a token from a local file.\r\nfunc tokenFromFile(file string) (*oauth2.Token, error) {\r\n\tf, err := os.Open(file)\r\n\tdefer f.Close()\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\ttok := \u0026oauth2.Token{}\r\n\terr = json.NewDecoder(f).Decode(tok)\r\n\treturn tok, err\r\n}\r\n\r\n// Saves a token to a file path.\r\nfunc saveToken(path string, token *oauth2.Token) {\r\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\r\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\r\n\tdefer f.Close()\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"Unable to cache OAuth token: %v\", err)\r\n\t}\r\n\tjson.NewEncoder(f).Encode(token)\r\n}\r\n\r\n// OAuth2 : Use OAuth2\r\nfunc OAuth2() *http.Client {\r\n\tcredentialFile := \"credentials.json\"\r\n\tb, err := os.ReadFile(credentialFile)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"Unable to read client secret file: %v\", err)\r\n\t}\r\n\tconfig, err := google.ConfigFromJSON(b, docs.DocumentsScope)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"Unable to parse client secret file to config: %v\", err)\r\n\t}\r\n\tclient := getClient(config)\r\n\treturn client\r\n}\r\n\r\nfunc main() {\r\n\tdocumentID := \"###\" // Please set here\r\n\ttableIndex := 0     // Please set here\r\n\r\n\tclient := OAuth2()\r\n\tg := gdoctableapp.New()\r\n\r\n\tres, err := g.Docs(documentID).TableIndex(tableIndex).GetValues().Do(client)\r\n\r\n\tif err != nil {\r\n\t\tfmt.Println(err)\r\n\t\tos.Exit(1)\r\n\t}\r\n\tfmt.Println(res.Values)\r\n}\r\n```\r\n\r\n## 2. Use Service account\r\n\r\nDocument of Service account is [here](https://developers.google.com/identity/protocols/OAuth2ServiceAccount). When you use Service account, please share Google Document with the email of Service account.\r\n\r\n### Sample script\r\n\r\n```golang\r\npackage main\r\n\r\nimport (\r\n\t\"encoding/json\"\r\n\t\"fmt\"\r\n\t\"io/ioutil\"\r\n\t\"log\"\r\n\t\"net/http\"\r\n\t\"os\"\r\n\r\n\tgdoctableapp \"github.com/tanaikech/go-gdoctableapp\"\r\n\t\"golang.org/x/oauth2\"\r\n\t\"golang.org/x/oauth2/google\"\r\n\t\"golang.org/x/oauth2/jwt\"\r\n\tdocs \"google.golang.org/api/docs/v1\"\r\n)\r\n\r\n// ServiceAccount : Use Service account\r\nfunc ServiceAccount(credentialFile string) *http.Client {\r\n\tb, err := ioutil.ReadFile(credentialFile)\r\n\tif err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\tvar c = struct {\r\n\t\tEmail      string `json:\"client_email\"`\r\n\t\tPrivateKey string `json:\"private_key\"`\r\n\t}{}\r\n\tjson.Unmarshal(b, \u0026c)\r\n\tconfig := \u0026jwt.Config{\r\n\t\tEmail:      c.Email,\r\n\t\tPrivateKey: []byte(c.PrivateKey),\r\n\t\tScopes: []string{\r\n\t\t\tdocs.DocumentsScope,\r\n\t\t},\r\n\t\tTokenURL: google.JWTTokenURL,\r\n\t}\r\n\tclient := config.Client(oauth2.NoContext)\r\n\treturn client\r\n}\r\n\r\nfunc main() {\r\n\tdocumentID := \"###\" // Please set here\r\n\ttableIndex := 0     // Please set here\r\n\r\n\tclient := ServiceAccount(\"credential.json\") // Please set here\r\n\tg := gdoctableapp.New()\r\n\r\n\tres, err := g.Docs(documentID).TableIndex(tableIndex).GetValues().Do(client)\r\n\r\n\tif err != nil {\r\n\t\tfmt.Println(err)\r\n\t\tos.Exit(1)\r\n\t}\r\n\tfmt.Println(res.Values)\r\n}\r\n```\r\n\r\n# Sample scripts\r\n\r\n- [Creating a Table to Google Document by Retrieving Values from Google Spreadsheet for Golang](https://gist.github.com/tanaikech/0589a673cae9569181def8ccd10793cf)\r\n\r\n# Limitations\r\n\r\n- In the current stage, unfortunately, `tableCellStyle` cannot be modified by Google Docs API. By this, the formats of cells cannot be modified. About this, I have posted as [Feature Request](https://issuetracker.google.com/issues/135136221).\r\n\r\n# References:\r\n\r\n- Official document: [Inserting or deleting table rows](https://developers.google.com/docs/api/how-tos/tables#inserting_or_deleting_table_rows)\r\n- If you want to know the relationship between the index and startIndex of each cell, you can see it at [here](https://stackoverflow.com/a/56944149).\r\n\r\n---\r\n\r\n\u003ca name=\"licence\"\u003e\u003c/a\u003e\r\n\r\n# Licence\r\n\r\n[MIT](LICENCE)\r\n\r\n\u003ca name=\"author\"\u003e\u003c/a\u003e\r\n\r\n# Author\r\n\r\n[Tanaike](https://tanaikech.github.io/about/)\r\n\r\nIf you have any questions and commissions for me, feel free to tell me.\r\n\r\n\u003ca name=\"updatehistory\"\u003e\u003c/a\u003e\r\n\r\n# Update History\r\n\r\n- v1.0.0 (July 18, 2019)\r\n\r\n  1. Initial release.\r\n\r\n- v1.0.5 (January 21, 2020)\r\n\r\n  1. When the inline objects and tables are put in the table. An error occurred. This bug was removed by this update.\r\n\r\n- v1.1.0 (January 22, 2020)\r\n\r\n  1. [2 new methods were added.](#replacetexts) From this version, the texts can be replaced by images. The direct link and local file can be used as the image.\r\n\r\n- v1.1.0 (April 18, 2023)\r\n\r\n  1. Confirmed all methods and updated the sample scripts. All methods works fine.\r\n\r\n[TOP](#top)\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftanaikech%2Fgo-gdoctableapp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftanaikech%2Fgo-gdoctableapp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftanaikech%2Fgo-gdoctableapp/lists"}