Home > Back-end >  How to export collumns into a word document in google script?
How to export collumns into a word document in google script?

Time:12-04

for example: i would like to take A, C, D columns of a spreadsheet named workstuff into a seperate word file. How would one do that? Lets say that they are in range 4:200. Thank you :)

CodePudding user response:

Script with comments:

function sample() {
  let spreadsheet = SpreadsheetApp.openById("documentId"); // open spreadsheet
  let sheet = spreadsheet.getSheetByName("sheetTabName"); // get the tab
  let values = sheet.getRange("A4:D200").getValues(); // load A, B, C and D
  values = values.map(row => [row[0], row[2], row[3]]); // remove B
  values = values.map(row => row.map(cell => ''   cell)); // convert to string

  let doc = DocumentApp.create("my-new-document"); // create new document
  doc.getBody().appendTable(values); // write values into table in the document
  doc.saveAndClose(); // Save and close it

  // Convert google document to word document
  let token = ScriptApp.getOAuthToken();
  var docBlob = UrlFetchApp.fetch('https://docs.google.com/feeds/download/documents/export/Export?id='   doc.getId()   '&exportFormat=docx',
    {
      headers: {
        Authorization: 'Bearer '   token
      }
    }).getBlob();

  // save word document it on drive
  var file = DriveApp.createFile(docBlob).setName('my-new-document.docx');
  DriveApp.addFile(file);
}

You may get the spreadsheet ID from url like:

https://docs.google.com/spreadsheets/d/SJKf90ahisfq8ewfyio32jasf890sadj3/edit#gid=4531234

The ID is: SJKf90ahisfq8ewfyio32jasf890sadj3

  • Related