簡體   English   中英

在Google文檔中的表格中插入和刪除文本

[英]Insert and remove text in Table within Google Docs

我有一個包含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單元格第2行中查找文本並將其替換為'Hello !! R3C3'

這是我如何將文本插入到Google文檔中的特定表格單元中的方法:

首先“查找”文檔中的表格:

  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','');
  }

因此,我希望這對尋求類似解決方案的其他人會有所幫助。

添加到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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM