如何在Google Apps Script中实现表格单元格与字体颜色同步至Web应用
解决方案:同步Google Sheet单元格背景色与字体颜色到Web应用
1. 修改Google Apps Script(Gs代码)
扩展getData函数,同时获取单元格的背景色和字体颜色,与文本数据一起返回:
function doGet(request) { return HtmlService.createTemplateFromFile('Index').evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL); } function include(filename) { return HtmlService.createHtmlOutputFromFile(filename) .getContent(); } function getData(){ const sheet = SpreadsheetApp.getActive().getSheetByName("Foglio1"); const dataRange = sheet.getDataRange(); // 获取文本内容、背景色、字体颜色 const values = dataRange.getDisplayValues(); const bgColors = dataRange.getBackgrounds(); const fontColors = dataRange.getFontColors(); // 映射数据,包含文本、背景色、字体颜色 const data = values.map((row, rowIndex) => { return { "AUDIOLIBRI": row[0], "bgColor": bgColors[rowIndex][0], "fontColor": fontColors[rowIndex][0] } }); // 移除表头行 data.shift(); return data; }
2. 修改Index.html
在表格<td>标签中通过Vue动态样式绑定,将颜色数据应用到单元格:
<!DOCTYPE html> <html> <head> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14"> </script> </head> <body> <div id="app"> {{ message }} <table class="w3-table-all"> <thead> <tr class="w3-light-grey"> <th>Audible</th> </tr> </thead> <template v-for="(item, index) in mydata" :key="index"> <tr> <!-- 动态绑定背景色和字体颜色 --> <td :style="{ backgroundColor: item.bgColor, color: item.fontColor }"> {{ item.AUDIOLIBRI }} </td> </tr> </template> </table> </div> <?!= include('Vue'); ?> </body> </html>
3. Vue.html无需修改
原有Vue逻辑可直接使用,只需接收新增的颜色字段:
<script> var app = new Vue({ el: '#app', data: { message: 'Prova', mydata : [ ], }, created: function () { google.script.run.withSuccessHandler(this.onSuccess).getData(); }, methods:{ onSuccess: function (serverData){ this.mydata= serverData } } }) </script>
关键说明
getBackgrounds()和getFontColors()返回二维数组,对应工作表每个单元格的十六进制颜色值(如#ffffff)- Vue的
:style指令支持对象格式的样式绑定,直接将颜色值应用到单元格 - 给
v-for的key使用index避免渲染警告,若数据有唯一标识也可替换为对应字段
内容的提问来源于stack exchange,提问作者Alessandro93
相关产品推荐
相关产品推荐

