HtmlService table not supporting line breaks and hyperlinks from spreadsheet

左心房为你撑大大i 提交于 2019-12-10 23:34:00

问题


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 e.g. 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>

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/33524540/htmlservice-table-not-supporting-line-breaks-and-hyperlinks-from-spreadsheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!