Motive
python gspread
を使って色付きのシートを作成する方法をまとめてみました。
Method
PythonでGoogleスプレッドシートに結合cellを作成する方法と同様に batch_update
メソッドを使ってjsonから直接書き込む手法を取ります。
value.json
{
"requests": [
{
"addSheet": {
"properties": {
"title": "開発環境",
"gridProperties": {
"rowCount": 3,
"columnCount": 3
},
"tabColor": {
"red": 1.0,
"green": 0.3,
"blue": 0.4
}
}
}
}
]
}
setting.ini
[googleSpreadSheet]
book_id = {{ スプレッドシートのID }}
keyfile_name = {{認証に必要なjsonファイル}}.json
import configparser
import json
import os
import json
from oauth2client.service_account import ServiceAccountCredentials
import gspread
def main():
config = configparser.ConfigParser()
ini_file = os.path.join("./", 'setting.ini')
config.read(ini_file)
scope = ["https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/drive"]
book_id = config.get("googleSpreadSheet", "book_id")
path = os.path.join("./", config.get("googleSpreadSheet", "keyfile_name"))
credentials = ServiceAccountCredentials.from_json_keyfile_name(path, scope)
client = gspread.authorize(credentials)
gfile = client.open_by_key(book_id)
dst = {}
with open("value.json", encoding='utf-8') as fin:
dst = json.load(fin)
gfile.batch_update(dst)
if __name__ == "__main__":
main()
Future
gspread
にある add_worksheet
メソッドにcolorの引数があると可能なのですが、現在はタイトルとシートの範囲指定くらいしかできません。 github には下記の通りになっています。
def add_worksheet(self, title, rows, cols):
"""Adds a new worksheet to a spreadsheet.
:param title: A title of a new worksheet.
:type title: str
:param rows: Number of rows.
:type rows: int
:param cols: Number of columns.
:type cols: int
:returns: a newly created :class:`worksheets <gsperad.models.Worksheet>`.
"""
body = {
'requests': [{
'addSheet': {
'properties': {
'title': title,
'sheetType': 'GRID',
'gridProperties': {
'rowCount': rows,
'columnCount': cols
}
}
}
}]
}
data = self.batch_update(body)
properties = data['replies'][0]['addSheet']['properties']
worksheet = Worksheet(self, properties)
return worksheet
もし引数を追加することになった時はdef add_worksheet(self, title, rows, cols, red=255, green=128, blue=0):
とRGBを別々に設定する方法があるのですが、htmlのカラーコードが馴染みがありそうなので下記とおりにした方がいいのかもしれません。
def add_worksheet(self, title, rows, cols, color=None):
red = 0.8
green = 0.8
blue = 0.8
if color is not None:
red = int("0x{}".format(color[1:3]),16)
green = int("0x{}".format(color[3:5]),16)
blue = int("0x{}".format(color[5:]),16)
body = {
'requests': [{
'addSheet': {
'properties': {
'title': title,
'sheetType': 'GRID',
'gridProperties': {
'rowCount': rows,
'columnCount': cols
}
}
}
}]
}
if color is not None:
body["requests"][0]["addSheet"]["properties"]["tabColor"] = {"red": red,"green": green,"blue": blue}
data = self.batch_update(body)
properties = data['replies'][0]['addSheet']['properties']
worksheet = Worksheet(self, properties)
return worksheet
issuesにでもリクエストするか。