发布到 Google 网站时如何保留 Google 电子表格中的换行符?

Han*_*y94 6 google-sites google-sheets google-apps-script

我有一个关于 Google 应用脚本的脚本。这个脚本简单地查找数据。

我的代码:

var content=this.spreadsheet.getSheetByName("sheet1").getRange("C1:C26").getValues();
this.summary = contents[4][0];
Run Code Online (Sandbox Code Playgroud)

我找到了我的数据,没有问题,但是,我的数据有换行符,我在 Google 网站上的网页显示的结果没有换行符。

这是一个使用 GetValue () 转换的概率吗?


我在电子表格单元格上的数据:

blabab---
bla
abla---

bla
Run Code Online (Sandbox Code Playgroud)

Google 网站上的结果

blabab---bla abla---bla

Chr*_*ice 4

解决方案如下:

  1. 获取您想要发布到 Google 网站的字符串(在单元格中)。
  2. 将字符串中的所有换行符 ( \n) 替换为 HTML 版本 ( <br />)

像下面这样:

function lineBreakTest() {
  var cellWithLineBreaks = SpreadsheetApp.getActiveSheet().getRange("a1").getValue();
  Logger.log(cellWithLineBreaks);

  cellWithLineBreaks = cellWithLineBreaks.replace(/\n/g, '<br>');

  Logger.log(cellWithLineBreaks);

  // Post to your Google Site here. Logger.log is just used to demonstrate.

}
Run Code Online (Sandbox Code Playgroud)

您必须这样做的原因是因为电子表格\n在其单元格中使用正常的文本换行符。然而,Google 网站使用 HTML 格式,因此您需要进行“转换”。这个答案也是一个有用的来源。