Servizio Documenti avanzato

Script per leggere, modificare e formattare i contenuti in Documenti Google con funzionalità aggiuntive.

Il servizio avanzato Documenti ti consente di utilizzare l'API Google Docs in Google Apps Script. Analogamente al servizio integrato Documenti di Apps Script, questa API consente agli script di leggere, modificare e formattare i contenuti in Google Docs. Nella maggior parte dei casi, il servizio integrato è più facile da usare, ma questo servizio avanzato offre alcune funzionalità aggiuntive.

Si tratta di un servizio avanzato che devi abilitare prima dell'uso. Segui la guida rapida per istruzioni passo passo su come iniziare.

Riferimento

Per informazioni dettagliate su questo servizio, consulta la documentazione di riferimento dell'API Docs. Come tutti i servizi avanzati in Apps Script, il servizio avanzato Docs utilizza gli stessi oggetti, metodi e parametri dell'API pubblica. Per saperne di più, consulta la sezione Come vengono determinate le firme dei metodi.

Per segnalare problemi e trovare altro supporto, consulta la guida all'assistenza dell'API Docs.

Codice di esempio

Il seguente codice di esempio utilizza la versione 1 dell'API.

Crea documento

Questo esempio crea un nuovo documento.

advanced/docs.gs
/**
 * Create a new document.
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create
 * @return {string} documentId
 */
function createDocument() {
  // Create document with title
  const document = Docs.Documents.create({ title: "My New Document" });
  console.log(`Created document with ID: ${document.documentId}`);
  return document.documentId;
}

Ricerca e sostituzione di testo

Questo esempio trova e sostituisce coppie di testo in tutte le schede di un documento. Questa opzione può essere utile quando sostituisci i segnaposto in una copia di un documento modello con i valori di un database.

advanced/docs.gs
/**
 * Performs "replace all".
 * @param {string} documentId The document to perform the replace text operations on.
 * @param {Object} findTextToReplacementMap A map from the "find text" to the "replace text".
 * @return {Object} replies
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
 */
function findAndReplace(documentId, findTextToReplacementMap) {
  const requests = [];
  for (const findText in findTextToReplacementMap) {
    const replaceText = findTextToReplacementMap[findText];

    // Replace all text across all tabs.
    const replaceAllTextRequest = {
      replaceAllText: {
        containsText: {
          text: findText,
          matchCase: true,
        },
        replaceText: replaceText,
      },
    };

    // Replace all text across specific tabs.
    const _replaceAllTextWithTabsCriteria = {
      replaceAllText: {
        ...replaceAllTextRequest.replaceAllText,
        tabsCriteria: {
          tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],
        },
      },
    };
    requests.push(replaceAllTextRequest);
  }
  const response = Docs.Documents.batchUpdate(
    { requests: requests },
    documentId,
  );
  const replies = response.replies;
  for (const [index] of replies.entries()) {
    const numReplacements =
      replies[index].replaceAllText.occurrencesChanged || 0;
    console.log(
      "Request %s performed %s replacements.",
      index,
      numReplacements,
    );
  }
  return replies;
}

Inserire e formattare il testo

Questo esempio inserisce un nuovo testo all'inizio della prima scheda del documento e lo formatta con un carattere e una dimensione specifici. Tieni presente che, se possibile, devi raggruppare più operazioni in un'unica chiamata batchUpdate per maggiore efficienza.

advanced/docs.gs
/**
 * Insert text at the beginning of the first tab in the document and then style
 * the inserted text.
 * @param {string} documentId The document the text is inserted into.
 * @param {string} text The text to insert into the document.
 * @return {Object} replies
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
 */
function insertAndStyleText(documentId, text) {
  const requests = [
    {
      insertText: {
        location: {
          index: 1,
          // A tab can be specified using its ID. When omitted, the request is
          // applied to the first tab.
          // tabId: TAB_ID
        },
        text: text,
      },
    },
    {
      updateTextStyle: {
        range: {
          startIndex: 1,
          endIndex: text.length + 1,
        },
        textStyle: {
          fontSize: {
            magnitude: 12,
            unit: "PT",
          },
          weightedFontFamily: {
            fontFamily: "Calibri",
          },
        },
        fields: "weightedFontFamily, fontSize",
      },
    },
  ];
  const response = Docs.Documents.batchUpdate(
    { requests: requests },
    documentId,
  );
  return response.replies;
}

Leggi il primo paragrafo

Questo esempio registra il testo del primo paragrafo della prima scheda del documento. A causa della natura strutturata dei paragrafi nell'API Docs, questa operazione comporta la combinazione del testo di più elementi secondari.

advanced/docs.gs
/**
 * Read the first paragraph of the first tab in a document.
 * @param {string} documentId The ID of the document to read.
 * @return {Object} paragraphText
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get
 */
function readFirstParagraph(documentId) {
  // Get the document using document ID
  const document = Docs.Documents.get(documentId, {
    includeTabsContent: true,
  });
  const firstTab = document.tabs[0];
  const bodyElements = firstTab.documentTab.body.content;
  for (let i = 0; i < bodyElements.length; i++) {
    const structuralElement = bodyElements[i];
    // Print the first paragraph text present in document
    if (structuralElement.paragraph) {
      const paragraphElements = structuralElement.paragraph.elements;
      let paragraphText = "";

      for (let j = 0; j < paragraphElements.length; j++) {
        const paragraphElement = paragraphElements[j];
        if (paragraphElement.textRun !== null) {
          paragraphText += paragraphElement.textRun.content;
        }
      }
      console.log(paragraphText);
      return paragraphText;
    }
  }
}

Best practice

Aggiornamenti batch

Quando utilizzi il servizio Docs avanzato, combina più richieste in un array anziché chiamare batchUpdate in un ciclo.

Non chiamare batchUpdate in un loop.

var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
  Docs.Documents.batchUpdate({
    requests: [{
      replaceAllText: ...
    }]
  }, docId);
}

Fai: chiama batchUpdate con una serie di aggiornamenti.

var requests = [];
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
  requests.push({ replaceAllText: ... });
}

Docs.Documents.batchUpdate({
  requests: requests
}, docId);