I am trying to create a table in a Doc file using Google Appsscript.
The last row should only consist of one cell:
但我能得到的就是这个(最后一行靠左对齐)。
我尝试了不同的事情:
- 使用 merge() 合并两个单元格会再次生成第二个图像
- 创建两个表并尝试合并它们会在行之间留下间隙。
- 更改最后一行的宽度会更改整个第一列的宽度
非常感谢您的帮助。
多谢!
var cells = [
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
["Only one Cell"]
];
var tableHeader = body.appendTable(cells);
问题和解决方法:
- 根据我的经验,我曾经有过
merge()
不能使用合并单元格的方法。我不确定这是一个错误还是当前的规范。现在,当我再次测试相同的情况时,似乎merge()
仍不能使用。而且,我也向你证实了同样的结果。我希望这个问题将在未来的更新中得到解决。
但幸运的是,人们已经发现,当使用 Google Docs API 时,可以合并表格单元格。因此,在这个答案中,我想建议使用 Google Docs API 来实现您的目标。当你的放映脚本修改后,下面的修改如何?
修改后的脚本:
在使用此脚本之前,请在高级 Google 服务中启用 Docs API https://developers.google.com/apps-script/guides/services/advanced#enable_advanced_services.
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var id = doc.getId();
var cells = [ // This is from your script.
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
['Cell 1', 'Cell 2'],
["Only one Cell"]
];
var length = cells.length;
cells[length - 1].push("");
body.appendTable(cells);
doc.saveAndClose();
// Use Google Docs API.
var obj = Docs.Documents.get(id).body.content;
var table = obj.reverse().find(({ table }) => table);
var requests = [{ mergeTableCells: { tableRange: { columnSpan: 2, rowSpan: 1, tableCellLocation: { tableStartLocation: { index: table.startIndex }, rowIndex: cells.length - 1, columnIndex: 0 } } } }];
Docs.Documents.batchUpdate({ requests }, doc.getId());
}
Testing:
运行此脚本时,将获得以下结果。
参考:
- 方法:documents.get https://developers.google.com/docs/api/reference/rest/v1/documents/get
- 方法:documents.batchUpdate https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
- 合并表格单元格请求 https://developers.google.com/docs/api/reference/rest/v1/documents/request#mergetablecellsrequest
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)