【问题标题】:How to get text color formatting from Google Sheets API?如何从 Google Sheets API 获取文本颜色格式?
【发布时间】:2021-08-06 00:09:36
【问题描述】:

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

Screenshot of the google sheet

Screenshot of Site generated from sheet

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

<?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();
  
?>

虽然它没有从工作表中获取颜色和格式信息。我想从谷歌表中获取文本颜色以显示在网站上(如“La Pomme”的红色) - 因为它可用于指示句子的元素(主语、动词、宾语顺序等) google sheet api可以做到这一点吗?

谢谢,

托马斯


更新的代码:在函数 getRes() 中使用 Tanaike 的解决方案从 Google Sheets 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 google-sheets formatting google-sheets-api


    【解决方案1】:

    我相信你的目标如下。

    • 您想检索单元格中部分文本的字体颜色。
    • 您希望使用 googleapis for php 来实现此目的。
    • 您已经能够使用 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

    注意:

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

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      相关资源
      最近更新 更多