Erase content in Google Apps Script Document Servi

2020-03-19 02:51发布

问题:

How to flush a document in Google Apps Script Document Service? Do I need to loop through all the kind of elements e.g. paragraph, image, table and remove them as a child? Is there an easier way to delete everything in the body of a document?

Thank you!

回答1:

According to the Documentation, the Document.setText should be able to clear the document content. I assume the following command should do it.

doc.setText('');


回答2:

In the current Document of google apps script as doc.setText method is not available this could be achieved by doc.getBody().clear()



回答3:

Counter intuitively (but, as documented) setText("") clears more than the text, it removes images as well.



回答4:

May i mention that the body.clear() method does not remove bookmarks, because they are associated with the document.

This worked for me:

scratchBody = scratchDoc.getBody();
scratchBody.clear();
bookmarks   = scratchDoc.getBookmarks();
while ( bookmarks.length ) { bookmarks.shift(); }

I didn't try this yet, but as with the bookmarks, there could be the HeaderSection, the FooterSection, and the FootnoteSections remaining in the document.