Преобразование XLS в CSV только для «новых» файлов - PullRequest
1 голос
/ 13 марта 2020

У меня есть:

  • .xlsx файлы, автоматически импортируемые ежедневно в папку на диске Google

Я хочу :

  • каждый файл конвертируется в CSV и сохраняется в другую папку

  • каждый файл конвертируется в Google Sheet и сохраняется в другая папка

  • исходный файл xlsx не удален

  • НО только для файлов, которые были добавлены с момента последнего запуска сценария

Я собрал приведенный ниже код из этого поста "Разархивировать файл, только если Новое в скрипте Google Apps" и из этого поста "Преобразование всех файлов в папке на диске из листы в CSV и добавить в новую папку ". Однако у меня есть проблема - когда я пытаюсь запустить это, я получаю сообщение об ошибке

GoogleJsonResponseException: API-вызов к drive.files.copy завершился ошибкой: файл не найден: [Name of SheetsFolder ]

Кто-нибудь может сказать, что это за ошибка, посмотрев на этот код?

function makeCSV() {
  //Add folder ID to select the folder where excel files are placed
  var SourceFolder = DriveApp.getFolderById("12XqAVzwzgl4a7Z1s6zn5VRcHiZ1vQdsT")
  //Add folder ID to save the where csv files to be placed
  var DestinationFolder = DriveApp.getFolderById("1Z_mUXs3FFDTN7XLk8EN9D5QOxVD8lZfB")
  //Add folder ID to save where the google sheets to be placed
  var SheetsFolder = DriveApp.getFolderById("17k_bl7Of2jH3U_TjaiiY_8BBOds4uSbT")

  //Select the XLS and XLSX files from source folder using the Mimetype of Microsoft Excel
  var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" + MimeType.MICROSOFT_EXCEL_LEGACY + "'";
  var sourceFiles = SourceFolder.searchFiles(searchQuery);

  var now = new Date(); //get current time after you fetch the file list from Drive.

  //Get script properties and check for stored "last_execution_time"
  var properties = PropertiesService.getScriptProperties();
  var cutoff_datetime = properties.getProperty('last_execution_time');

  //if we have last execution date, stored as a string, convert it to a Date object.
  if(cutoff_datetime)
     cutoff_datetime = new Date(cutoff_datetime);

  //Loop over all the XLS files
  while (sourceFiles.hasNext()){
    var sourceFile = sourceFiles.next();

    //if no stored last execution, or file is newer than last execution, process the file.
    if(!cutoff_datetime || file.getDateCreated() > cutoff_datetime){
      var fileId = sourceFile.getId();

      //Copy the XLS file to the Sheets Folder as a google sheet 
      var spreadsheet = Drive.Files.copy({mimeType: MimeType.GOOGLE_SHEETS, parents: [{id: SheetsFolder}]}, fileId);

      //Get the data from the google sheet using the SpreadsheetApp
      var sheets = SpreadsheetApp.openById(spreadsheet.id).getSheets();sheets[0].getDataRange().getValues()

      //Create a csv file using the data from the google sheet     
      var csv = sheets.map(function(sheet) {return sheet.getDataRange().getValues().reduce(function(csv, row) {return csv += row.join(",") + "\n"}, "")}); DestinationFolder.createFile(spreadsheet.title + ".csv", csv, MimeType.CSV)
    }
  }

  //store "now" as last execution time as a string, to be referenced on next run.
  properties.setProperty('last_execution_time',now.toString());
} 

Любая помощь очень ценится!

РЕДАКТИРОВАТЬ 1: Спасибо Tanaike за помощь в устранении неполадок! В приведенном выше коде было две проблемы: одна из них была той, на которую Танайке указал в своем комментарии. Второе - это то, что «file» должен читать «sourceFile» в операторе if. Ниже выкладываю правильный код для потомков.

function makeCSV() {
  //Add folder ID to select the folder where excel files are placed
  var SourceFolder = DriveApp.getFolderById("12XqAVzwzgl4a7Z1s6zn5VRcHiZ1vQdsT")
  //Add folder ID to save the where csv files to be placed
  var DestinationFolder = DriveApp.getFolderById("1Z_mUXs3FFDTN7XLk8EN9D5QOxVD8lZfB")
  //Add folder ID to save where the google sheets to be placed
  var SheetsFolder = DriveApp.getFolderById("17k_bl7Of2jH3U_TjaiiY_8BBOds4uSbT")

  //Select the XLS and XLSX files from source folder using the Mimetype of Microsoft Excel
  var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" + MimeType.MICROSOFT_EXCEL_LEGACY + "'";
  var sourceFiles = SourceFolder.searchFiles(searchQuery);

  var now = new Date(); //get current time after you fetch the file list from Drive.

  //Get script properties and check for stored "last_execution_time"
  var properties = PropertiesService.getScriptProperties();
  var cutoff_datetime = properties.getProperty('last_execution_time');

  //if we have last execution date, stored as a string, convert it to a Date object.
  if(cutoff_datetime)
     cutoff_datetime = new Date(cutoff_datetime);

  //Loop over all the XLS files
  while (sourceFiles.hasNext()){
    var sourceFile = sourceFiles.next();

    //if no stored last execution, or file is newer than last execution, process the file.
    if(!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime){
      var fileId = sourceFile.getId();

      //Copy the XLS file to the Sheets Folder as a google sheet 
      var spreadsheet = Drive.Files.copy({mimeType: MimeType.GOOGLE_SHEETS, parents: [{id:"17k_bl7Of2jH3U_TjaiiY_8BBOds4uSbT"}]}, fileId);

      //Get the data from the google sheet using the SpreadsheetApp
      var sheets = SpreadsheetApp.openById(spreadsheet.id).getSheets();sheets[0].getDataRange().getValues()

      //Create a csv file using the data from the google sheet     
      var csv = sheets.map(function(sheet) {return sheet.getDataRange().getValues().reduce(function(csv, row) {return csv += row.join(",") + "\n"}, "")}); DestinationFolder.createFile(spreadsheet.title + ".csv", csv, MimeType.CSV)
    }
  }

  //store "now" as last execution time as a string, to be referenced on next run.
  properties.setProperty('last_execution_time',now.toString());
} 
...