我有一个包含3x4表格的Google文档。我需要从函数中删除并添加这些表格单元格中的文本。
我可以使用以下代码索引所有表格单元格值:
var searchElement = copyBody.findElement(DocumentApp.ElementType.TABLE);
var element = searchElement.getElement();
var table = element.asTable();
var tablerows = element.getNumRows();
for ( var row = 0; row < tablerows; ++row ) {
var tablerow = element.getRow(row)
for ( var cell=0; cell < tablerow.getNumCells(); ++cell) {
var celltext = tablerow.getChild(cell).getText();
Logger.log( "Text is ("+celltext+")" );
logg提出以下内容:
[16-01-19 01:23:31:663 PST] Text is (A)
[16-01-19 01:23:31:665 PST] Text is (C)
[16-01-19 01:23:31:666 PST] Text is (E)
[16-01-19 01:23:31:667 PST] Text is (X)
[16-01-19 01:23:31:669 PST] Text is (Row 2, Cell 1)
[16-01-19 01:23:31:670 PST] Text is (Row 2, Cell 2)
[16-01-19 01:23:31:672 PST] Text is (Row 2, Cell 3)
[16-01-19 01:23:31:673 PST] Text is (Row 2, Cell 4)
[16-01-19 01:23:31:675 PST] Text is (Row 3, Cell 1)
[16-01-19 01:23:31:677 PST] Text is (Row 3, Cell 2)
[16-01-19 01:23:31:678 PST] Text is (Row 3, Cell 3)
[16-01-19 01:23:31:679 PST] Text is (Row 3, Cell 4)
我以前用过这个来插入文本(自由格式,不在表格单元格中):
function insertText() {
var body = DocumentApp.getActiveDocument().getBody();
var val = body.findText('Hello! R3C3');
if(val == null)
{
var text = body.editAsText();
text.insertText(9, 'Hello! R3C3');
}
else
{
body.replaceText('Hello! R3C3','');
}
}
问题:如何找到并替换第2行,第1行中的文字'Hello! R3C3'?
答案 0 :(得分:1)
以下是我如何将文字插入Google文档中的特定表格单元格
首先找到&#39;文件中的表格:
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
var searchElement = copyBody.findElement(DocumentApp.ElementType.TABLE);
var element = searchElement.getElement();
var table = element.asTable();
var tablerows = element.getNumRows();
要插入/删除文字,请使用以下内容:
//Row3Cell3
var Row3Cell3 = table.getRow(2).getCell(2).getChild(0).getText();
if(Row3Cell3 != 'Hello! R3C3')
{
var Row3Cell3_1 = table.getRow(2).getCell(2).getChild(0);
Row3Cell3_1.setText('Hello! R3C3');
}
else
{
copyBody.replaceText('Hello! R3C3','');
}
所以我希望这对寻求类似解决方案的其他人有所帮助。
答案 1 :(得分:0)
添加到John,如果您已经拥有所需的表,则可以通过以下方式编辑单元格文本:
table.getRow(rowIdx).getChild(colIdx).asText().setText('Your text here');
因此,在您的示例中(第2行,单元格1):
table.getRow(1).getChild(0).asText().setText('Hello R3C3!');
参考: https://developers.google.com/apps-script/reference/document/table(getRow和getChild)