python - 如何使用 pygsheets 旋转 Google 表格中的文本?

标签 python pygsheets

我正在尝试使用 python 中的 pygsheets 旋转 Google 表格中一些长标题名称的文本。下面的代码显示了对 pygsheets 中提供的示例的轻微修改,根据 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()

结果: resulting spreadsheet

最佳答案

  • 您希望将 Sheets API 的“textRotation”与 pyghseets 结合使用。

如果我的理解是正确的,这个答案怎么样?在我的环境中,我也可以确认发生了与您相同的问题。所以当我看到“pygsheets”的脚本时,我注意到了该脚本的修改点。

虽然设置了textRotation的参数,但遗憾的是,textRotation并未包含在请求体中。这样,textRotation 就不起作用了。

修改后的脚本:

当您使用此修改时,请将已安装的“pygsheets”目录中的cell.pyget_json()修改如下。我认为可能还有更简单的修改。因此,请将此视为多个答案之一。

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”通过上述修改有效。但如果这在您的环境中不起作用,我深表歉意。

关于python - 如何使用 pygsheets 旋转 Google 表格中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56641290/

相关文章:

python - 拆分大量字符串并创建结果列表

python - 将数组转换为 CSV,包括多行图像

python - pygsheets 上次访问或上次修改时间戳

python - 使用pygsheets使用service_file授权方法创建一个全新的sheet

google-drive-api - 如何使用 PyGSheets v2 在特定文件夹/目录中创建新工作表?

python - pyqt4 和 pyserial

python - QComboBox使用QQueryModel,从点击中获取id字段(不显示)

python - 如何找到似乎没有在任何地方定义的 python 模块?

python - 未定义名称 'WorksheetNotFound'