如何 get/create 仅在单元格的一部分中添加超链接?

How do I get/create a hyperlink in only part of a cell?

我想弄清楚如何仅在 Google 电子表格单元格的一部分中获取或创建超链接。例如,如果我的单元格是用 markdown 编写的,它将如下所示:

Device ID, found on [the inventory website](https://www.example.com/)

我试过方法CellFormat#getHyperlinkDisplayType()CellData#getHyperlink(),都返回null。我检查了调试器中的所有单元格数据,但没有看到 URL 出现在任何地方。这让我有理由相信我需要在 setFields 方法中包含另一个字段:

Sheets sheets = auth.getService();
Get request = sheets.spreadsheets().get(id).setFields(
"sheets.properties,sheets.data.rowData.values(effectiveValue,effectiveFormat.backgroundColor)");
Spreadsheet response = request.execute();

我不确定哪个字段会包含超链接,也找不到可用字段的列表。我也希望能够创建一个只覆盖单元格中部分文本的超链接。

这可能吗?

我相信你的目标如下。

  • 您想使用工作表 API.

    在单元格的部分文本中检索或创建 hyperlink
  • 作为示例情况,您想要从以下 Spreadsheet 情况的单元格“B1”中检索 https://www.example.com/。而且,您想创建像单元格“B1”这样的情况。

    Row Column A Column B
    1 Device ID found on the inventory website

问题和解决方法:

遗憾的是,在当前阶段,还没有使用 Sheets API 在单元格的部分文本中检索和创建 hyperlink 的方法。因此,在这个答案中,我想提出一个解决方法来实现您的目标。 在此解决方法中,由 Google Apps Script 创建的 Web 应用程序用作包装器。因为当使用Google Apps Script的Spreadsheet服务时,可以直接达到你的目的。 Web 应用程序的使用方式类似于 API。因此,此解决方法的流程如下。

  1. 在客户端,请求 Web 应用程序。
  2. 在 Web Apps 端,使用 Google Apps Script 在单元格的部分文本中检索并创建 hyperlink。
  3. Return结果传给客户端

要使用此解决方法,请执行以下流程。

用法:

1。创建 Google Apps 脚本的新项目。

Web 应用程序的示例脚本是 Google 应用程序脚本。所以请创建一个 Google Apps 脚本的项目。

如果要直接创建,请访问https://script.new/。在这种情况下,如果您未登录 Google,则会打开登录屏幕。所以请登录Google。这样,Google Apps Script 的脚本编辑器就打开了。

2。准备 Web 应用程序端。 (服务器端)

请将以下脚本(Google Apps 脚本)复制并粘贴到脚本编辑器并保存项目。此脚本用于 Web 应用程序。此 Web 应用程序用作 API.

// This function is used for retrieving the hyperlinks from a sheet in a Google Spreadsheet.
function doGet(e) {
  let returnValue = "";
  const {method, spreadsheetId, sheetName} = e.parameter;
  if (method == "get") {
    const res = getHyperlinks(spreadsheetId, sheetName);
    returnValue = JSON.stringify(res);
  } else {
    returnValue = "Error: No method.";
  }
  return ContentService.createTextOutput(returnValue);
}

// This function is used for creating a cell including the hyperlinks in a part of cell text on a sheet in a Google Spreadsheet.
function doPost(e) {
  let returnValue = "";
  const {method, spreadsheetId, sheetName} = e.parameter;
  if (method == "create") {
    if (e.postData) {
      const res = createHypetlinks(spreadsheetId, sheetName, JSON.parse(e.postData.contents));
      returnValue = JSON.stringify(res);
    } else {
      returnValue = "Error: No object for creating hyperlink in a cell.";
    }
  } else {
    returnValue = "Error: No method.";
  }
  return ContentService.createTextOutput(returnValue);
}

function createHypetlinks(spreadsheetId, sheetName, object) {
  const ss = SpreadsheetApp.openById(spreadsheetId);
  const sheet = ss.getSheetByName(sheetName);
  const range = sheet.getRange(object.rowIndex + 1, object.columnIndex + 1);
  const builder = SpreadsheetApp.newRichTextValue().setText(object.cellText);
  object.hyperlinks.forEach(({startIndex, endIndex, url}) => builder.setLinkUrl(startIndex, endIndex, url));
  range.setRichTextValue(builder.build());
  return "Done.";
}

function getHyperlinks(spreadsheetId, sheetName) {
  const ss = SpreadsheetApp.openById(spreadsheetId);
  const sheet = ss.getSheetByName(sheetName);
  const richTextValues = sheet.getDataRange().getRichTextValues();
  const hyperlinks = richTextValues.reduce((ar, r, i) => {
    r.forEach((c, j) => {
      const temp = c.getRuns().reduce((arr, r) => {
        const link = r.getLinkUrl();
        if (link) {
          arr.push({text: r.getText(), hyperlink: link});
        }
        return arr;
      }, []);
      if (temp.length > 0) {
        ar.push({rowIndex: i, columnIndex: j, hyperlinks: temp});
      }
    });
    return ar;
  }, []);
  return hyperlinks;
}

3。部署 Web 应用程序。

详细信息见the official document

  1. 在脚本编辑器上,在脚本编辑器的右上角,点击“点击部署”->“新建部署”。
  2. 请点击“Select类型”->“网络应用程序”。
  3. 请在“部署配置”下的字段中输入有关 Web 应用程序的信息。
  4. 请select“我”“执行为”
    • 这是此解决方法的重要性。
  5. 请 select “任何人” “谁有权访问”
    • 在这种情况下,用户不需要使用访问令牌。所以请用这个作为测试用例。
    • 当您要使用访问令牌时,请将其设置为Anyone with Google accountOnly myself。这样,用户就可以使用访问令牌访问 Web 应用程序。当您使用access token时,请包含https://www.googleapis.com/auth/drive.readonlyhttps://www.googleapis.com/auth/drive的范围。
  6. 请点击“部署”按钮。
  7. 当显示“Web App 要求您授权访问您的数据”时,请点击“授权访问”。
  8. 自动打开“需要授权”的对话框。
    1. Select自己的账号。
    2. 点击“此应用未验证”处的“高级”。
    3. 点击“转到###项目名称###(不安全)”
    4. 单击“允许”按钮。
  9. 复制Web App的URL。就像 https://script.google.com/macros/s/###/exec
    • 当您修改 Google Apps 脚本时,请重新部署为新版本。这样,修改后的脚本就会反映到 Web 应用程序中。请注意这一点。

3。正在测试。

作为一个简单的测试,当它使用curl命令向Web Apps请求时,变成如下。请设置您的 Web 应用程序 URL、方法、传播 sheet ID 和 sheet 名称,以及请求正文。正确部署 Web 应用程序后,将返回值。

从 sheet 检索 hyperlinks。
$ curl -L 'https://script.google.com/macros/s/###/exec?method=get&spreadsheetId={your Spreadsheet ID}&sheetName=Sheet1'
  • rowIndexcolumnIndex的起始索引为0。例如,rowIndex: 1columnIndex: 1 是单元格“B2”;

  • 当你的Web Apps部署正确,你的curl命令正确,spreadsheet有toptable的样本时,得到如下结果。

      [
        {
          "rowIndex":0,
          "columnIndex":1,
          "hyperlinks":[{"text":"the inventory website","hyperlink":"https://www.example.com/"}]
        }
      ]
    
创建一个包含 hyperlinks 的单元格。
$ curl -L -d '{"rowIndex": 0, "columnIndex": 2, "cellText": "found on the inventory website", "hyperlinks": [{"startIndex": 9, "endIndex": 30, "url": "https://www.example.com/"}]}' 'https://script.google.com/macros/s/###/exec?method=create&spreadsheetId={your Spreadsheet ID}&sheetName=Sheet1'
  • startIndexendIndex的起始索引为0。因此,例如,当单元格文本为 sample text 并且您想将 link 赋给 text 时,startIndexendIndex7 并且11,分别;

  • 当上述示例 curl 命令为 运行 时,found on the inventory website 被放入单元格“C1”并且 the inventory website 具有 hyperlink https://www.example.com/如下。并且,你可以在控制台看到Done.

注:

  • 当您修改Web Apps的脚本时,请将Web Apps重新部署为新版本。由此,最新的脚本被反​​映到Web Apps。请注意这一点。

参考文献: