Home > Enterprise >  Google Sheets table is not showing new lines "\n" correctly in App Script WebApp
Google Sheets table is not showing new lines "\n" correctly in App Script WebApp

Time:09-26

I have a simple WebApp for getting a table data in a Spreadsheet.

What's the problem is, I have not getting Line Breaks in WebApp

Actual Data in Spreadsheet

Akash
Bangalore

but getting like this in WebApp

Akash Bangalore

Pls help me to do this ..

Spreadsheet URL

WebApp URL

Below is the Code.gs file

function doGet() {
  template = HtmlService.createTemplateFromFile('Index.html');
  return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

  var spreadsheetId   = '116XVmxdI5uQ4A2QsjLrI25pUQBCDL22KCkGXHZZfKVQ';

  var sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName("Sheet1") ;

  var dataValues = sheet.getDataRange().getDisplayValues() ;

Below is the Index.html file

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1>Display Google Sheet Web App</h1>
    <table border="1" style="border-collapse: collapse; margin:auto"  cellpadding="5px" >
      <?var tableData = dataValues ?>
      <?for(var i = 0; i < tableData.length; i  ) { ?>
      <?if(i == 0) { ?>
        <tr>
        <?for(var j = 0; j < tableData[i].length; j  ) { ?>
        <th><?= tableData[i][j] ?></th>
        <? } ?>
        </tr>
      <? } else { ?>
        <tr>
        <?for(var j = 0; j < tableData[i].length; j  ) { ?>
        <td><?= tableData[i][j] ?></td>
        <? } ?>
        </tr>
      <? } ?>
      <? } ?>
    </table>
  </body>
</html>

CodePudding user response:

New lines \n in html are ignored. To get breaks in html, you should use <br/>. Use Array.map to loop:

var dataValues = sheet.getDataRange()
    .getDisplayValues()
    .map(row => row.map(value =>
          value.replace(/\n/g, `<br/>`)
        )
     );

CodePudding user response:

When passing a value to be displayed, i.e. as <?= tableData[i][j] ?> instead of printing scriptlets <?= ?> use force-printing scriptlets <?!= ?>

The above because when using the first, Google use contextual escaping, while with the other Google will show the data "as is".

  • Related