Reputation: 479
I tried to add a new row in an existing table inside Google doc file but the table property is not applied to the new row. I was able to save 2 cells with styling. Here's the Apps Script function
function addRow(fileId)
{
var body = DocumentApp.openById(fileId).getBody(),
searchElement = body.findElement(DocumentApp.ElementType.TABLE),
element = searchElement.getElement(),
table = element.asTable();
var cell1Style = table.getRow(0).getCell(0).getAttributes();
var cell2Style = table.getRow(0).getCell(1).getAttributes();
cell1Style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ffffff';
cell2Style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ffffff';
var rowStyle = {};
rowStyle[DocumentApp.Attribute.BORDER_COLOR] = '#000000';
var tr = table.appendTableRow();
tr.setAttributes(rowStyle);
tr.appendTableCell('My Text:').setAttributes(cell1Style);
tr.appendTableCell('My value').setAttributes(cell2Style);
}
Here's the document content after execution
As you can see the new row came outside the table even though i have set border color attribute. Please help
Upvotes: 0
Views: 570
Reputation: 2760
Here is how you do this:
function myFunction() {
var body = DocumentApp.getActiveDocument().getBody();
var table = body.findElement(DocumentApp.ElementType.TABLE).getElement().asTable();
var newRow = table.appendTableRow();
var lastRowAttributes = table.getRow(table.getNumRows()-1).getAttributes()
newRow.appendTableCell("Text 1").setAttributes(lastRowAttributes);
newRow.appendTableCell("Text 2").setAttributes(lastRowAttributes);
}
If that doesn't work for you, you can use:
function myFunction() {
var body = DocumentApp.getActiveDocument().getBody();
var table = body.findElement(DocumentApp.ElementType.TABLE).getElement().asTable();
var lastRow = table.getRow(table.getNumRows()-1);
var newRow = table.appendTableRow(lastRow.copy());
newRow.getCell(0).setText("Text 1");
newRow.getCell(1).setText("Text 2");
}
I decided to use the style of the last row (before appending) as the style for the following rows to save time.
Hope this helps!
Upvotes: 2