Retrieving Named Functions from Google Spreadsheet using Google Apps Script

Gists

Retrieving Named Functions from Google Spreadsheet using Google Apps Script

This is a sample script for retrieving the named functions from Google Spreadsheet using Google Apps Script.

Recently, the named functions got to be able to be used in Google Spreadsheet. Ref When several named functions are added, I thought that I wanted to retrieve these functions using a script. But, unfortunately, in the current stage, it seems that there are no built-in methods (SpreadsheetApp and Sheets API) for directly retrieving the named functions. So, I created this sample script.

In this script, the following flow is run.

  1. Convert Google Spreadsheet to XLSX format.
  2. Retrieve the data from XLSX data.
  3. Parse XLSX data and retrieve the named functions.

Sample script

function myFunction() {
  const spreadsheetId = "###"; // Please set Spreadsheet ID.

  // Convert Google Spreadsheet to XLSX format.
  const ss = SpreadsheetApp.openById(spreadsheetId);
  const url = `https://docs.google.com/spreadsheets/export?exportFormat=xlsx&id=${ss.getId()}`;
  const resHttp = UrlFetchApp.fetch(url, {
    headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
  });

  // Retrieve the data from XLSX data.
  const blobs = Utilities.unzip(resHttp.getBlob().setContentType(MimeType.ZIP));
  const workbook = blobs.find((b) => b.getName() == "xl/workbook.xml");
  if (!workbook) {
    throw new Error("No file.");
  }

  // Parse XLSX data and retrieve the named functions.
  const root = XmlService.parse(workbook.getDataAsString()).getRootElement();
  const definedNames = root
    .getChild("definedNames", root.getNamespace())
    .getChildren();
  const res = definedNames.map((e) => ({
    definedName: e.getAttribute("name").getValue(),
    definedFunction: e.getValue(),
  }));
  console.log(res);

  // DriveApp.getFiles(); // This comment line is used for automatically detecting the scope of Drive API.
}

Testing

When this script is run to the top sample situation, the following result is obtained.

[
  {
    "definedName": "CONTAINS",
    "definedFunction": "LAMBDA(cell, range, NOT(ISERROR(MATCH(cell,range,0))))"
  },
  { "definedName": "SAMPLE1", "definedFunction": "LAMBDA(range, SUM(range))" }
]

Note

 Share!