Spencer
Spencer

Reputation: 457

Google Docs Apps Script get number of columns

On a Google Doc you can set columns from Format > Columns. Now, though, I want to access those columns from Apps Script to confirm the number of columns. I don't even need to modify them, just access. I haven't found anything that jumps out at me from the documentation, so I didn't know if there's an extension of the Document service that would allow for such. I'm sorry not to include any code, but I have no code obvious to show. I did create a document with 2 columns to see exactly what I'm talking about. https://docs.google.com/document/d/1MyttroeN4kPUm9PfYZnTe_gJqstM3Gb5q3vS3c84dNw/edit

Upvotes: 0

Views: 989

Answers (2)

Alexander Joseph
Alexander Joseph

Reputation: 1

You can do this without the advanced service using try-catch:

function numCols(table) {
  cols = 0;
  table = table.asTable();
  while (true) {
    try {
      table.getColumnWidth(cols);
      cols++;
    } catch {break;}
  }
  return cols;
}

Upvotes: 0

fullfine
fullfine

Reputation: 1461

Answer

It is possible using the get method of the Google Docs API

How to do it

  1. In Apps Script, enable the Advanced Docs Service.
  2. Use the method get.
  3. Check the array called content.
  4. Search an object called sectionBreak in each element of content.
  5. Check that the object has the following data: sectionBreak>sectionStyle>columnProperties.
  6. Take the length of the array columnProperties.
  7. (keep in mind that the first occurrence of columnProperties is in the first element of content, skip it and start the loop from the second one.

Code

function myFunction() {
  var id = DocumentApp.getActiveDocument().getId()
  var result = Docs.Documents.get(id)
  var content = result["body"]["content"]
  for (var i = 1; i < 20; i++) {
    try {
      var cols = content[i]["sectionBreak"]["sectionStyle"]["columnProperties"]
      console.log('number of columns: ' + cols.length)
    } catch (error) {
    }

  }
}

Reference

Upvotes: 2

Related Questions