google-apps-script - 使用 Apps 脚本将 HTML 表格(用户输入)更新到 Google 表格
问题描述
我正在尝试将 HTML 表(用户输入)附加到 Google 表格。我读了这篇文章,但解决方案对我不起作用。我在 Apps Script 中启用了 Google Sheets API。我可以使用 appendrow 来更新每次单击的每一行,但我期待通过单击来附加整个表。
HTML 前端。
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table id="t01">
<tr>
<th>Project</th>
<th>Current Light Type</th>
<th>Qty</th>
</tr>
<tr>
<td><input type="text" id="p1" size="25"></td>
<td>
<select id="l1">
<option>2D</option>
<option>Donwlight</option>
</select>
</td>
<td><input type="text" id="q1" size="25"></td>
</tr>
<tr>
<td><input type="text" id="p2" size="25"></td>
<td>
<select id="l2">
<option>2D</option>
<option>Donwlight</option>
</select>
</td>
<td><input type="text" id="q2" size="25"></td>
</tr>
</table>
<div>
<button id="btn">Submit</button>
</div>
<script>
document.getElementById("btn").addEventListener("click",parse_to_backend);
function parse_to_backend(){
let table = document.getElementById("t01").outerHTML;
google.script.run.pasteHtml(table);
document.getElementById("p1").value="";
document.getElementById("l1").value="";
document.getElementById("q1").value="";
};
</script>
</body>
</html>
JS 后端
function doGet(e) {
return HtmlService.createTemplateFromFile("page").evaluate();
}
function pasteHtml(table) {
var url = "https://docs.google.com/spreadsheets/d...";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
var req = {
requests: [
{
pasteData: {
html: true,
data: table,
coordinate: {
sheetId: ws,
rowIndex: 0,
columnIndex: 0,
},
},
},
],
};
Sheets.Spreadsheets.batchUpdate(req, ws);
}
解决方案
你很近。从您引用的答案中,您没有维护两件关键的事情。
- 的值
sheetId
需要是工作表的 ID,而不是工作表ws
- 该
Sheets.Spreadsheets.batchUpdate()
调用需要电子表格 ID,而不是电子表格本身。
function pasteHtml(table) {
var url = "https://docs.google.com/spreadsheets/d...";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
var req = {
requests: [
{
pasteData: {
html: true,
data: table,
coordinate: {
sheetId: ws.getSheetId(), // Pass the sheet ID
rowIndex: 0,
columnIndex: 0,
},
},
},
],
};
Sheets.Spreadsheets.batchUpdate(req, ss.getId()); // Pass the spreadsheet ID
}
现在,由于您在前端代码中提取表格的方式(因为它实际上是表格中的输入),您将遇到一些其他问题,但这有效。如果您对如何提取表格/输入数据有其他问题,请发布另一个问题并添加 javascript 标签,以便其他人可以帮助您。
推荐阅读
- r - 从 knitr 输出中删除进度条
- amazon-web-services - Spring Boot - 不同的系统(eureka、zuul、ribbon、nginx)用于什么?
- arrays - 从存储在 React 状态中的对象数组访问属性
- sass - 用于开发和生产的 Grunt-contrib-sass?
- c# - 使用 AJAX 联系服务器上的方法
- regex - 所有有效文档类型标签的正则表达式匹配字符串
- javascript - 在 JavaScript 中格式化 JSON 对象
- ios - 更改标签栏项目的顺序
- r - 无法在 R 中检测到 unicode
- android - gradle 3.2.1 的数据绑定问题