php - 使用 Google Sheets API 查找工作表尺寸

标签 php google-sheets-api

我正在使用 API 连接到 Google 工作表,并希望找出该工作表的最大(现有)尺寸,以便提取所有数据

$service = new Google_Service_Sheets($client);
// would really like to calculate range
$range = 'Sheet1!A1:Z100';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);

有没有办法确定工作表的最大现有尺寸,甚至获取整个工作表,以便我可以更精确地预先计算我需要的单元格范围?

最佳答案

我相信您的目标和目前的情况如下。

  • 您想要检索 Google 电子表格中特定工作表的所有值。
  • 您想要检索 Google 电子表格中特定工作表的单元格总数。
  • 您希望使用 PHP 的 googleapis 来实现此目的。
  • 您已经能够使用 Sheets API 从 Google 电子表格获取值。

修改点:

  • 为了检索 Google 电子表格中特定工作表的所有值,不需要使用范围 a1Notation。在这种情况下,您可以使用工作表名称作为范围来检索所有值。
  • 为了从Google Spreadsheet中的特定工作表中检索单元格总数,我认为可以使用使用spreadsheets.get方法检索每个工作表的gridPropertiesgridProperties 对象具有 rowCountcolumnCount 属性。我认为这些属性可以用来计算细胞总数。

当以上几点反射(reflect)到您的脚本中时,它会变成如下所示。

修改后的脚本1:

在此修改中,所有值均从特定工作表中检索。你的脚本修改一下,变成如下。

$service = new Google_Service_Sheets($client);
// would really like to calculate range
$range = 'Sheet1'; // Modified
$response = $service->spreadsheets_values->get($spreadsheetId, $range);

修改后的脚本2:

在此修改中,从特定工作表中检索单元格总数。你的脚本修改一下,就变成下面这样了。本例中使用的是spreadsheets.get方法。

$service = new Google_Service_Sheets($client);
// would really like to calculate range
$range = 'Sheet1';
$response = $service->spreadsheets->get($spreadsheetId, ["ranges" => [$range], "fields" => "sheets(properties(gridProperties(columnCount,rowCount)))"]);
$gridProperties = $response[0] -> getProperties() -> getGridProperties();
$rowCount = $gridProperties -> getRowCount();
$columnCount = $gridProperties -> getColumnCount();
$totalNumberOfCells = $rowCount * $columnCount;
print($totalNumberOfCells);
  • 作为fields的值,我使用了sheets(properties(gridProperties(columnCount,rowCount)))

  • 如果您想检索 Google 电子表格中所有工作表中的单元格总数,您还可以使用以下脚本。

      $spreadsheetId = "###";  // Please set the Spreadsheet ID.
      $response = $service->spreadsheets->get($spreadsheetId, ["fields" => "sheets(properties(gridProperties(columnCount,rowCount)))"]);
      $totalNumberOfCells = 0;
      foreach ($response as $i => $sheet) {
          $gridProperties = $sheet -> getProperties() -> getGridProperties();
          $rowCount = $gridProperties -> getRowCount();
          $columnCount = $gridProperties -> getColumnCount();
          $totalNumberOfCells += $rowCount * $columnCount;
      }
      print($totalNumberOfCells);
    

引用文献:

关于php - 使用 Google Sheets API 查找工作表尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67336050/

相关文章:

google-sheets-api - 使用 Spreadsheets.batchUpdate 和 AppendCellsRequest 忽略列样式

javascript - 与嵌入式 Google Apps 电子表格交互

php - 比给定日期时间早一小时

php - 在 PHP 中返回格式化数字

php - PHP 的 password_hash() 行为

javascript - 从谷歌电子表格中特定范围的单元格获取json数据

javascript - 从谷歌表格获取数据适用于 jsfiddle 但不适用于本地客户端

python - 使用 Python 更新 Google Sheet APIv4 中的值

php - 单选按钮表单代码和下拉菜单代码

php - Elasticsearch 查询 - 带空格的短语