多个 line/multiple 链接单元格中的自动超链接

Auto hyperlink in multiple line/multiple links cell

从 CSV 文件导入的大文件(+1k 行)。 文件有一列文件地址如下:

http://www.whatever.whatever/file1.jpg

有些行在所述列中有一个以上的文件地址,用“换行符”分隔,所以有些行是

http://www.whatever.whatever/file2.jpg
http://www.whatever.whatever/file3.jpg
http://www.whatever.whatever/file4.jpg

等等...

具有 1 个地址的行被 google 张自动转换为 hyperlink,这正是我想要的。 具有多个文件地址的行保留原样,这就是问题所在。 如何自动 link 具有多个文件地址的行,而不必逐一进行? 谢谢

可以参考这个示例代码:

function addHyperlink(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var links = sheet.getRange(1,1,sheet.getLastRow(),1).getValues().flat();

  links.forEach((cellLink,index) => {
    Logger.log(cellLink);
    Logger.log(cellLink.includes('\n'));
    
    //Check if cell value has multiple links (contains line break)
    if(cellLink.includes('\n')){
      var tmpUrl = cellLink.split('\n');
      var rText = SpreadsheetApp.newRichTextValue().setText(cellLink);
      var startOffset = 0;
      tmpUrl.forEach(url=>{
        Logger.log(url);
        Logger.log(url.length);
        Logger.log(startOffset);
        rText.setLinkUrl(startOffset,(startOffset+url.length),url);
        startOffset = startOffset + url.length + 1;
      });
      var value = rText.build();
      sheet.getRange(index + 1,1).setRichTextValue(value);
    }
  });

}

它有什么作用?

  1. 获取 A 列中的所有单元格值。使用 array.flat()
  2. 将二维数组更改为一维数组值
  3. 使用 array.includes()
  4. 检查每个值是否包含换行符
  5. 如果找到多个 url,将每个 url 拆分为一个临时数组变量。
  6. 创建 RichTextValueBuilder using SpreadsheetApp.newRichTextValue(). Set the text based on the original cell's value using setText(text)
  7. 循环每个个体 url 以获得其 url 长度,用于使用 setLinkUrl(startOffset, endOffset, linkUrl) 设置超链接的 start offsetend offset。每次处理 url 时调整 start offset
  8. 使用build() to generate a RichTextValue. Set the cell range rich text value using setRichTextValue(value)

输出:

之前:

之后: