Как повернуть текст в Google Sheet с помощью таблиц? - PullRequest
0 голосов
/ 18 июня 2019

Я пытаюсь повернуть текст некоторых длинных имен заголовков в Google Sheet, используя pygsheets в python.Приведенный ниже код демонстрирует небольшую модификацию примеров, представленных в таблицах, которые в соответствии с docs должны работать.Текст пишется в правильные ячейки, ячейка A1 выделена жирным шрифтом, но ячейки B1 и C1 не повернуты.Сообщение об ошибке не появляется.Есть идеи, почему это не работает?

import pygsheets

sheet_url = "https://docs.google.com/spreadsheets/d/1t3nYyvkVkf6E36vTRucRQ35XQWbeRC--6U5h1chtikI"
gc = pygsheets.authorize(service_file = "credentials.json")
sh = gc.open_by_url(sheet_url)
wks = sh.worksheet("title", "Sheet1")

header = wks.cell('A1')
header.value = 'Bold Text'
header.set_text_format('bold', True)
header.update()

header2 = wks.cell('B1')
header2.value = '45 Degree rotated text'
header2.set_text_rotation('angle', 45)
header2.update()

header3 = wks.cell('C1')
header3.value = 'Vertical Text'
header3.set_text_rotation('vertical', True)
header3.update()

Результат: итоговая таблица

1 Ответ

1 голос
/ 18 июня 2019
  • Вы хотите использовать "textRotation" Sheets API с pyghseets.

Если мое понимание верно, как насчет этого ответа?В моем окружении я также могу подтвердить, что такая же проблема с вами произошла.Поэтому, когда я увидел скрипт "pygsheets", я заметил, что точка модификации скрипта.

Хотя параметры для textRotation установлены, к сожалению, textRotation не входит в тело запроса.Таким образом, textRotation не работает.

Модифицированный скрипт:

Когда вы используете эту модификацию, пожалуйста, измените get_json() из cell.py в каталоге установленных "pygsheets"следующее.Я думаю, что может быть более простая модификация.Поэтому, пожалуйста, подумайте об этом, как об одном из нескольких ответов.

def get_json(self):
    """Returns the cell as a dictionary structured like the Google Sheets API v4."""
    try:
        nformat, pattern = self.format
    except TypeError:
        nformat, pattern = self.format, ""

    if self._formula != '':
        value = self._formula
        value_key = 'formulaValue'
    elif is_number(self._value):
        value = self._value
        value_key = 'numberValue'
    elif type(self._value) is bool:
        value = self._value
        value_key = 'boolValue'
    elif type(self._value) is str or type(self._value) is unicode:
        value = self._value
        value_key = 'stringValue'
    else:   # @TODO errorValue key not handled
        value = self._value
        value_key = 'errorValue'

    ret_json = dict()
    ret_json["userEnteredFormat"] = dict()

    if self.format[0] is not None:
        ret_json["userEnteredFormat"]["numberFormat"] = {"type": getattr(nformat, 'value', nformat),
                                                         "pattern": pattern}
    if self._color[0] is not None:
        ret_json["userEnteredFormat"]["backgroundColor"] = {"red": self._color[0], "green": self._color[1],
                                                            "blue": self._color[2], "alpha": self._color[3]}
    if self.text_format is not None:
        ret_json["userEnteredFormat"]["textFormat"] = self.text_format
        fg = ret_json["userEnteredFormat"]["textFormat"].get('foregroundColor', None)
        if fg:
            ret_json["userEnteredFormat"]["textFormat"]['foregroundColor'] = {"red": fg[0], "green": fg[1],
                                                                              "blue": fg[2], "alpha": fg[3]}

    if self.borders is not None:
        ret_json["userEnteredFormat"]["borders"] = self.borders
    if self._horizontal_alignment is not None:
        ret_json["userEnteredFormat"]["horizontalAlignment"] = self._horizontal_alignment.value
    if self._vertical_alignment is not None:
        ret_json["userEnteredFormat"]["verticalAlignment"] = self._vertical_alignment.value
    if self._wrap_strategy is not None:
        ret_json["userEnteredFormat"]["wrapStrategy"] = self._wrap_strategy

    ### Added -- begin
    if self.text_rotation is not None:
        ret_json["userEnteredFormat"]["textRotation"] = self.text_rotation
    ### Added -- end

    if self._note is not None:
        ret_json["note"] = self._note
    ret_json["userEnteredValue"] = {value_key: value}

    return ret_json

Результат:

Когда отразится вышеуказанная модификация, ваш скрипт получит следующий результат.

enter image description here

Примечание:

  • Этот измененный сценарий предполагает, что Sheets API уже можно использовать.
  • Я исследовал выше модификацию послеЯ обновил pygsheets до "pygsheets-2.0.1".

Ссылки:

В моей среде я могу подтвердить, что с помощью "textRotation" работает вышеуказанная модификация.Но если это не сработало в вашей среде, я прошу прощения.

...