如何从 Google 工作表 API 获取文本颜色格式?

How to get text color formatting from Google Sheets API?

我已经使用 api 为 php 网站设置了 Google 表格作为简单的后端。这是一个外语学习资源,所以人们可以添加/编辑句子。

Screenshot of the google sheet

Screenshot of Site generated from sheet

在生成每种语言页面的 template.php 顶部,我有这个脚本,然后我遍历 $sheetsValues 以在网站上制作 table。

<?php 

require __DIR__ . '/vendor/autoload.php';
  // connect to API
  $client = new \Google_Client();
  $client->setApplicationName('12Sentences');
  $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
  $client->setAccessType('offline');
  $client->setAuthConfig(__DIR__ . '/credentials.json');
  $service = new Google_Service_Sheets($client);
  $spreadsheetId = 'MY_SPREADSHEET_ID';

  $range = "$language!B3:E15";
  $response = $service->spreadsheets_values->get($spreadsheetId, $range );
  $sheetsValues = $response->getValues();
  
?>

虽然它没有从 sheet 中获取颜色和格式信息。我想从 google sheet 中获取文本颜色以在网站上显示(如 'La Pomme' 的红色)——因为它可用于指示句子的元素( google sheets api?

这可能吗?

谢谢,

托马斯


更新代码:在函数 getRes() 中使用下面的 Tanaike 解决方案从 Google 表格 API 获取颜色数据。然后调用 getFormattedHtml() 以获取 HTML 和 CSS 中的彩色文本。不优雅,但很适合我使用。

<?php

function getFormattedHtml($row, $column, $res) {
  $formattedHtml = "";
  // get plain text
  $plain_text = $res[$row][$column]['formattedValue'];

  // get textFormatRuns
  $textFormatRuns = $res[$row][$column]['textFormatRuns'];

  // loop over the textFormatRuns
  $len = count($textFormatRuns);
  for ($i=0; $i < $len; $i++) { 
    $currentRunStart = $textFormatRuns[$i]['startIndex'];
    $currentRunEnd = $textFormatRuns[$i + 1]['startIndex'];
    $substring = "";
    if ($i == $len - 1) {
      $substring = substr($plain_text, $currentRunStart);
    } else {
      $substring = substr($plain_text, $currentRunStart, $currentRunEnd - $currentRunStart);
    }
    
    $span = "";
    if (isset($textFormatRuns[$i]['format']['foregroundColor'])) {
      $red = $textFormatRuns[$i]['format']['foregroundColor']['red'] * 255;
      $green = $textFormatRuns[$i]['format']['foregroundColor']['green'] * 255;
      $blue = $textFormatRuns[$i]['format']['foregroundColor']['blue'] * 255;
      $span = "<span style=\"color:rgb($red, $green, $blue)\">$substring</span>";
    } else {
      $span = "<span>$substring</span>";
    }
    
    $formattedHtml .= $span;
  }

  return($formattedHtml);
}

function getRes() {
  require __DIR__ . '/vendor/autoload.php';
// connect to API
$client = new \Google_Client();
$client->setApplicationName('12Sentences');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/credentials.json');
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'MY_SPREADSHEET_ID';
$range = "$language!B3:E15";

// This script uses the method of "spreadsheets.get".
$sheets = $service->spreadsheets->get($spreadsheetId, ["ranges" => [$range], "fields" => "sheets"])->getSheets();

// Following script is a sample script for retrieving "textFormat" and "textFormatRuns".
$data = $sheets[0] -> getData();
$startRow = $data[0] -> getStartRow();
$startColumn = $data[0] -> getStartColumn();
$rowData = $data[0] -> getRowData();
$res = array();
foreach ($rowData as $i => $row) {
    $temp = array();
    foreach ($row -> getValues() as $j => $value) {
        $tempObj = [
            "row" => $i + 1 + $startRow,
            "column" => $j + 1 + $startColumn
        ];
        if (isset($value['formattedValue'])) {
            $tempObj['formattedValue'] = $value -> getFormattedValue();
        } else {
            $tempObj['formattedValue'] = "";
        }
        $userEnteredFormat = $value -> getUserEnteredFormat();
        if (isset($userEnteredFormat['textFormat'])) {
            $tempObj['textFormat'] = $userEnteredFormat -> getTextFormat();
        } else {
            $tempObj['textFormat'] = null;
        }
        if (isset($value['textFormatRuns'])) {
            $tempObj['textFormatRuns'] = $value -> getTextFormatRuns();
        } else {
            $tempObj['textFormatRuns'] = null;
        }
        array_push($temp, $tempObj);
    }
    array_push($res, $temp);
}

  return($res);
}
?>

我相信你的目标如下。

  • 您想检索单元格中部分文本的字体颜色。
  • 您想使用 php 的 googleapis 实现此目的。
  • 您已经能够使用 Sheets API.
  • 从 Google 电子表格中获取值

修改点:

  • 在您的脚本中,使用了 Sheets API 中的“spreadsheets.values.get”方法。在这种情况下,不包括“textFormat”和“textFormatRuns”的值。为了检索单元格中文本部分的那些值,需要使用“spreadsheets.get”的方法。

当以上几点反映到你的脚本中,就会变成下面这样。

修改后的脚本:

$service = new Google_Service_Sheets($client);
$spreadsheetId = 'MY_SPREADSHEET_ID';
$range = "$language!B3:E15";

// This script uses the method of "spreadsheets.get".
$sheets = $service->spreadsheets->get($spreadSheetId, ["ranges" => [$range], "fields" => "sheets"])->getSheets();

// Following script is a sample script for retrieving "textFormat" and "textFormatRuns".
$data = $sheets[0] -> getData();
$startRow = $data[0] -> getStartRow();
$startColumn = $data[0] -> getStartColumn();
$rowData = $data[0] -> getRowData();
$res = array();
foreach ($rowData as $i => $row) {
    $temp = array();
    foreach ($row -> getValues() as $j => $value) {
        $tempObj = [
            "row" => $i + 1 + $startRow,
            "column" => $j + 1 + $startColumn
        ];
        if (isset($value['formattedValue'])) {
            $tempObj['formattedValue'] = $value -> getFormattedValue();
        } else {
            $tempObj['formattedValue'] = "";
        }
        $userEnteredFormat = $value -> getUserEnteredFormat();
        if (isset($userEnteredFormat['textFormat'])) {
            $tempObj['textFormat'] = $userEnteredFormat -> getTextFormat();
        } else {
            $tempObj['textFormat'] = null;
        }
        if (isset($value['textFormatRuns'])) {
            $tempObj['textFormatRuns'] = $value -> getTextFormatRuns();
        } else {
            $tempObj['textFormatRuns'] = null;
        }
        array_push($temp, $tempObj);
    }
    array_push($res, $temp);
}
print($res);

结果:

当以上脚本用于以下情况时,

得到如下结果

[
  [
    {
      "row":1,
      "column":1,
      "formattedValue":"sample1 sample2 sample3 sample4 sample5",
      "textFormat":{"bold":true},
      "textFormatRuns":[
        {"startIndex":8,"format":{"foregroundColor":{"red":1},"foregroundColorStyle":{"rgbColor":{"red":1}}}},
        {"startIndex":15,},
        {"startIndex":16,"format":{"foregroundColor":{"green":1},"foregroundColorStyle":{"rgbColor":{"green":1,}}}},
        {"startIndex":23,},
        {"startIndex":24,"format":{"foregroundColor":{"blue":1},"foregroundColorStyle":{"rgbColor":{"blue":1,}}}},
        {"startIndex":31,}]
    }
  ]
]
  • 以上面的结果为例,发现索引8到15的sample2是红色的
  • 关于上面结果中rgbColor的颜色,你可以在官方文档中看到详细信息。 Ref

注:

  • 这是一个简单的示例脚本。所以请根据您的实际情况修改以上内容。

参考: