Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a Spreadsheet in a particular folder via App Script

Can anybody help me out,

I want to create a Spreadsheet through App Script in a particular folder. How to do that.

Presently I am doing as follow:

var folder = DocsList.getFolder("MyFolder");
var sheet = SpreadsheetApp.create("MySheet");
var file = DocsList.getFileById(sheet.getId());
file.addToFolder(folder);
file.removeFromFolder(file.getParents()[0]);

It is not working.......

like image 370
Hari Das Avatar asked Oct 26 '13 13:10

Hari Das


People also ask

How do I add data to a Google spreadsheet using an app script?

The code uses the appendRow() method of the Sheet object to write a single row of data to the spreadsheet. To append a row, pass an array of values (corresponding to the columns) to the appendRow() method. For example, the code below appends a row containing two values: First name and Last name.


2 Answers

As suggested by @Joshua, it's possible to create a Spreadsheet (in a specific folder) with the Advanced Drive Service:

var name = 'your-spreadsheet-name'
var folderId = 'your-folder-id'
var resource = {
  title: name,
  mimeType: MimeType.GOOGLE_SHEETS,
  parents: [{ id: folderId }]
}
var fileJson = Drive.Files.insert(resource)
var fileId = fileJson.id

No need to move files around with this method !

like image 85
ozeebee Avatar answered Oct 05 '22 07:10

ozeebee


Since you can no longer create Google Docs (Docs or SpreadSheets) using DriveApp, nor use addToFolder because DocList is deprecated. There is only one way to create or "move" Google Docs or Google SpreadSheets..

  //"Move" file to folder-------------------------------//
  var fileID = '12123123213321'
  var folderID = '21321312312'
  var file = DriveApp.getFileById(fileID).getName()
  var folder = DriveApp.getFolderById(folderID)
  var newFile = file.makeCopy(file, folder)

  //Remove file from root folder--------------------------------//
  DriveApp.getFileById(fileID).setTrashed(true)

As you can see this DOES NOT move the file, it makes a copy with the same name in the folder you want and then moves the original file to the trash. I'm pretty sure there is no other way to do this.

like image 42
maeq Avatar answered Oct 05 '22 06:10

maeq