How do I copy & move a FORM to a folder in Google Apps Script?

微笑、不失礼 提交于 2020-06-26 16:22:15

问题


I know how to create a file into a folder (or rather move when talking about a spreadsheet, since we can not create them directly. Or can we?

So my questions:

1) I created a form in my script, how do I move it to a sub folder?

I've tried:

var formFile = DriveApp.getFileById(form.getId());
folder.createFile(formFile.getBlob());
DriveApp.removeFile(formFile);

but I received an error that I could not create a pdf file from a form.

2) Is there a way to create a spreadsheet directly into a folder?

All I found was this:

// create the file in the root
var spreadSheet = SpreadsheetApp.create(title + " (Response)");

// get a file (not a spreadsheet)
var ssFile = DriveApp.getFileById(spreadSheet.getId());

// copy the file into the folder
folder.createFile(ssFile.getBlob());

// delete the file from the root folder.
DriveApp.removeFile(ssFile);

There must be an easier way.

Thank you.


回答1:


You can create a new Form (Or other type of) file directly into a folder with the Advanced Drive Service. Previously, the Advanced Drive Service needed to be enabled before it could be used, but now it doesn't.

Code

var folderID = 'myFolderID_Here';

var fileResource = {
  title: 'myNewFile',
  "parents": [{'id':folderID}],  //<--By setting this parent ID to the folder's ID, it creates this file in the correct folder.
  mimeType: 'application/vnd.google-apps.form'
};

var newFile = Drive.Files.insert(fileResource);

Then you can get the ID of the new spreadsheet file with:

var theID = newFile.getId();
Logger.log('theID: ' + theID);

To enable the Advanced Drive Service, click the "Resources" menu, and choose Advanced Google Services.

If you want to get all the form responses out of a form, you'll need to use code something like this:

function getResponsesOutOfForm() {
  var frm = FormApp.openById('My_Form_ID');
  var allResponses = frm.getResponses();
  var arrayOfData = [], rowArray = [], theResponse, formResponse, itemResponses;

  for (var i = 0; i < allResponses.length; i++) {
    formResponse = allResponses[i];
    itemResponses = formResponse.getItemResponses();

    rowArray = []; //Reset inner array

    for (var j = 0; j < itemResponses.length; j++) {
      theResponse = itemResponses[j].getResponse();
      rowArray.push(theResponse);
    };

    arrayOfData.push(rowArray);
  };

  Logger.log(arrayOfData)
  return arrayOfData;
};


来源:https://stackoverflow.com/questions/35400790/how-do-i-copy-move-a-form-to-a-folder-in-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!