0

I'm trying to convert all CSV and Excel files in a folder to Google Sheet format. The code works, but debugging it produces an error.

function fileToSheet(fileId) {
 var file = DriveApp.getFileById(fileId);
 var fileInfo = {
   title: "(" + Utilities.formatDate(new Date(), "IST", "yyyy.mm.dd") + ") " + file.getName(),
   mimeType: MimeType.GOOGLE_SHEETS,
   parents: [{id: file.getParents().next().getId()}]
   }
 var blob = file.getBlob();
 var mimeType = blob.getContentType();
 
 if (mimeType == MimeType.CSV || mimeType == MimeType.MICROSOFT_EXCEL || mimeType == MimeType.MICROSOFT_EXCEL_LEGACY) {
    var spreadsheet = Drive.Files.insert(fileInfo, blob);
    Logger.log(spreadsheet.id)
  }
  return ""
}

function convertFiles(folderId) {
  var folder = DriveApp.getFolderById(folderId); 
  var files = folder.getFiles();
  Logger.log(files.length)

  while (files.hasNext()) {
    var file = files.next()
    var fileId = file.getId()
    fileToSheet(fileId)
  }
}
  1. Debugging and running it to the end still produces an error (Error Exception: Invalid argument: id fileToSheet @ Code.gs:2), but the code still works when I use it on folders.
  2. Is there any way to shorten the code to make it more concise? (still new to coding)

Thank you!

  • You say it "works when I use it on folders". Do you mean whan `fileToSheet(fileId)` is run from `convertFiles`? And how else are you running it so that the parameter `fileId` is set to a value? – TheWizEd Nov 12 '22 at 14:48
  • Yes, I meant it works when I've tested it with different google drive folders. I will get the folder's id and use it for the function convertfiles(folderId). – user20485973 Nov 12 '22 at 16:11

1 Answers1

0

Insert the following in the beginning of the fileToSheet() function:

function fileToSheet(fileId) {
  if (!fileId) {
    throw new Error(
      'Please do not run the fileToSheet() function in the script editor window. '
      + 'See https://stackoverflow.com/a/46860052/13045193 to learn how to '
      + 'debug the function properly.'
    );
  }
  var file = DriveApp.getFileById(fileId);
  // ...
doubleunary
  • 13,842
  • 3
  • 18
  • 51