简体   繁体   中英

HtmlService table not supporting line breaks and hyperlinks from spreadsheet

I am writing Google Apps Script to display data from spreadsheet into HTML table using HtmlService. But I faced below two challenges:

  1. If spreadsheet cell value has line breaks into it, table shows it as single line.
  2. If spreadsheet cell has hyperlink eg Link to Google Drive file, it shows it as plain text in table cell.

I tried writing spreadsheet cell value as <a href="url of file">File Name</a> , but still table read it as plain text without making hyperlink. Below is the HTML code.

How can I display spreadsheet cell values as it is with line breaks in HTML table? Also how to create hyperlinks in table for urls in spreadsheet cells?

    <table cellspacing="0" style="width:700px; background-color:#fdfbc4; table-layout:fixed; word-wrap: break-word ">
   <? for(var l=0; l< data_labels.length -1 ; l++){ ?>
       <tr>         
         <td> <?= data_labels[l] ?> </td> <td > <?= data[l] ?></td>        
       </tr>
   <? } ?>

   </table>

Assuming that you have a variable result that contains the text from a spreadsheet cell, you can replicate the line breaks for HTML by replacing them with <br> tags.

result = result.replace(/\n/g,"<br>");

In my own SheetConverter library, I also replace spaces with non-breaking spaces and encode < symbols to avoid having cell contents interpreted as HTML.

result = result.replace(/ /g,"&nbsp;").replace(/</g,"&lt;").replace(/\n/g,"<br>");

Part 2 of your question isn't readily answerable, in part because there are multiple ways to express a URL in spreadsheets.

  • If a cell contains a HYPERLINK() function, you can use Range.getFormula() to retrieve the formula, and get the URL and displayed text from that. However, the URL may be another formula or cell reference, so you could still end up with a non-viable link.

  • If a cell contains text that Google Sheets interprets as a URL or Email address, it will be marked as a link in the Sheets GUI, but neither the resulting formatting nor the HREF are available to Google Apps Script.

Feel free to examine the SheetConverter source and take ideas from it, or just use it as a library to simply your efforts.

A simple solution to show line breaks/spaces
use the html tag <pre>Data retreived here</pre>
You can then apply a css class to the pre element to change the predefined font.

The HTML Preformatted Text (<pre>) represents preformatted text. Text within this element is typically displayed in a non-proportional font exactly as it is laid out in the file. Whitespaces inside this element are displayed as typed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM