How to fix error - Invalid argument: file.contentType, when creating new Google Sheet

丶灬走出姿态 提交于 2020-12-07 04:59:04

问题


I am trying to create a new Google Sheet in a created folder, but am having issues with the content Type.

I have searched for this error but haven't found anything. Most searches come up with a MimeType error, but I don't think that's the issue. Below is the code I'm using:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var newFolder = DriveApp.getFolderById("MyID").createFolder("New Folder");
newFolder.createFile("myFileName",ss,MimeType.GOOGLE_DOCS);

Whenever I run this in my spreadsheet, I get the following error:

Invalid argument: file.contentType (line 3, file "Code")

I have tried using "" for the content for createFile.


回答1:


How about following sample? I cannot use MimeType of GOOGLE_SHEETS and GOOGLE_DOCS, too. I don't know why. So I propose use of SpreadsheetApp.create(). The flow is as follows.

  1. Create spreadsheet using SpreadsheetApp.create().

  2. Add destination folder information to the spreadsheet.

  3. Remove original folder information from the spreadsheet.

By this, you can create a spreadsheet to a folder you want.

Script:

var sheetfile = "myFileName";
var destfolder = "MyID";
var sheet = SpreadsheetApp.create(sheetfile);
var file = DriveApp.getFileById(sheet.getId());
var destfolder = DriveApp.getFolderById(destfolder).addFile(file);
var docfile = file.getParents().next().removeFile(file);

Updated: November 25, 2020

At July 27, 2020, the method of moveTo(destination) was added. And, the methods of addFile and removeFile will be deprecated. Ref So, when the method of moveTo(destination) is used for above script, it becomes as follows.

var sheetfile = "myFileName";
var destfolder = "MyID";
var sheet = SpreadsheetApp.create(sheetfile);
var file = DriveApp.getFileById(sheet.getId());
var destfolder = DriveApp.getFolderById(destfolder);
var docfile = file.moveTo(destfolder);
  • When the method of Files: insert of Drive API is used, the following script can be also used. Ref

      var sheetfile = "myFileName";
      var destfolder = "MyID";
      Drive.Files.insert({title: sheetfile, mimeType: MimeType.GOOGLE_SHEETS, parents: [{id: destfolder}]});
    



回答2:


I faced the same issue and instead of trying to create a file on the fly, I thought of having a cleaner solution where by I am keeping one empty spreadsheet (Just create a spreadsheet in the drive and name as "Template") as a template to make copies out of.

var templateFileId = "asfashfkhsfkhfkhkashf"; //This is something you have to define as a constant var destinationFolderId = "sdfashfkhaskf" var newSpreadsheet = DriveApp.getFileById(templateFileId).makeCopy("NewSpreadsheet", destinationFolderId);



来源:https://stackoverflow.com/questions/41992358/how-to-fix-error-invalid-argument-file-contenttype-when-creating-new-google

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