Google Apps脚本-分别运行但未结合运行时,两个功能/脚本可以工作

迪德里克

我正在研究更新XLS文件值的脚本。我只会添加我认为与问题相关的内容,但会告诉我是否需要更多信息。

我首先提交一个表单,该表单说明要添加的值,在何处添加以及有多少。然后,脚本将在提交表单时运行。

它首先将.XLS文件转换为.CSV文件,然后将CSV文件中的数据添加到Google电子表格中,同时在我已告知的位置添加值,以便一切正常进行。所有这些工作都很好,我可以看到每次在Google Sheet中更新值时以及在代码运行后它们都已更新。

完成后,我想将Google表格转换回XLS文件,然后将其放回到原来的文件夹中。第一次执行此操作时,XLS文件中的值已更新,但是第二次及其后每次更新都“滞后一个会话”。第二次我没有在新的XLS文件中获取更新的值,第三次我从第二次及以后获取更新的值。这仅发生在XLS文件上,而不在Google表格上发生。

仅当我手动运行导出XLS文件的代码/功能时,才会发生这种情况,并且所有这些都正常工作。但是,如果我在主代码后添加该函数,则会发生问题。

而且我试图在函数之间将代码暂停10秒钟,但得到的结果是相同的。


由于所有添加的值都可以在Google工作表中正常工作,因此我只添加文件类型转换的代码。我只说一下//之间发生的情况

这只是可以同时运行的函数,但没有提供具有最新更新值的XLS文件:

function test() {    

  newValuesToDatabase();
  updateALLITEMS();

}

将新值添加到该函数的功能(同时添加到不相关的其他电子表格和将成为XLS文件的电子表格)

function newValuesToDatabase() {


// FIRST FINDS OUT WHAT TO UPDATE FROM THE FORM SHEET 
// Ends up with "formX" array seen later in the code


// Opens and gets the data from another sheet I also want to update (Irrelevant sheet) 
// This ends up with the "itemDataBase" Array used later


// Gets the XLS file and turn it into CSV


    var workFolder = DriveApp.getFolderById( "(workFolderid)" ),
        backupFolder = DriveApp.getFolderById( "(backupFolderid)" );

    var oauthToken = ScriptApp.getOAuthToken(),
        sourceFolder = DriveApp.getFolderById( "(sourceFolderid)" ),
        mimes = [MimeType.MICROSOFT_EXCEL, MimeType.MICROSOFT_EXCEL_LEGACY];



    for (var m = 0; m < mimes.length; m++) {

      var files = sourceFolder.getFilesByType(mimes[m]);

        while (files.hasNext()) {

          var sourceFile = files.next();

          if (sourceFile.getName() == "ALL ITEMS") {

            console.log("File found")


            //Creates a backupfile to be put in a different folder
            var backupDate = (new Date).getDate() + ", " 
                           + (new Date).toString().split(" ")[1] + " " 
                           + (new Date).getYear();

            sourceFile.makeCopy(backupFolder).setName("backup on " + backupDate);
            sourceFile.setTrashed(true);


            var googleSheet = JSON.parse(UrlFetchApp.fetch(
                "https://www.googleapis.com/upload/drive/v2/files?uploadType=media&convert=true", {
                    method: "POST",
                    contentType: "application/vnd.ms-excel",
                    payload: sourceFile.getBlob().getBytes(),
                    headers: {
                        "Authorization": "Bearer " + oauthToken
                    }
                }
            ).getContentText());   


            // The exportLinks object has a link to the converted CSV file
            var targetFile = UrlFetchApp.fetch(
                googleSheet.exportLinks["text/csv"], {
                    method: "GET",
                    headers: {
                        "Authorization": "Bearer " + oauthToken
                    }
                });

            // Save the CSV file in a folder to be deleted in the end of the script when done with it
            var csvFile = workFolder.createFile(targetFile.getBlob()).setName(sourceFile.getName() + ".csv");

          }
        }
      } 





    // Finds the google sheet that later will be converted back to XLS:


     var checkSSFile = workFolder.getFilesByName("Update Items (ikke rør)");
     var checkID = checkSSFile.next().getId().toString();

     var addSpreadSheet = SpreadsheetApp.openById(checkID),
         addSheet = addSpreadSheet.getSheetByName("ALL ITEMS");



     // Gets the CSV file and makes an array from it

     var csvFile = workFolder.getFilesByType(MimeType.CSV).next();

     if (csvFile.getName() == "ALL ITEMS.csv") {

       var csvData = Utilities.parseCsv(csvFile.getBlob().getDataAsString());

     }



     function updateAmount() {  // ( This function is ran at the bottom of code )



       //Code first adds stuff to the irrelevant spreadsheet mentioned in the beginning of this code



       // Then gets the sheet that will be converted to XLS:

         var range = addSheet.getRange(1, 1, addSheet.getLastRow()+1, 2);
         range.clearContent(); //Empties sheet first so there are no overlap when adding everything over again


         //Code then adds the old and new values into that sheet in the right order and way

     }




   // Here is where the code is ran dependent on what the form says.


     if (formX[0][1] == "Add a new item of something we have from before") {

       updateAmount();

     } else if (formX[0][1] == "Add a completely new item") {

       //I have not added this function/code yet

     } else {

       console.log("Could not find a mode in the form submission");

     }


     csvFile.setTrashed(true); //Then trashes the csv file in the end
}

然后,将其转换回并放置在正确位置的函数:

function updateALLITEMS() {

  var workFolder = DriveApp.getFolderById( "(workFolderid)" );
  var checkSS = workFolder.getFilesByName("Update Items (ikke rør)");
  var checkID = checkSS.next().getId().toString();

  var sourceFolder  = DriveApp.getFolderById( "(sourceFolderid)" ),
      file          = DriveApp.getFileById(checkID),
      url           = 'https://docs.google.com/spreadsheets/d/'+checkID+'/export?format=xlsx';
  var token         = ScriptApp.getOAuthToken();

  var newAllItems      = UrlFetchApp.fetch(url, {
    method: "GET",
    payload: file.getBlob().getBytes(),
    headers: {
        'Authorization': 'Bearer ' +  token
      }
  });


  // Then add "ALL ITEMS" XLS file back to where it was
  sourceFolder.createFile(newAllItems.getBlob()).setName("ALL ITEMS"); 


   //This deletes files that appear on the main GDrive folder, don't know why. 
   //These files are named "Unknown", and are copies of the Google Sheet I'm working on

  var ss = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS); 
  while (ss.hasNext()) {
    var sht = ss.next();
    if (sht.getName() == "Untitled") {

      var shtID = sht.getId();
      var checkSht1 = SpreadsheetApp.openById(shtID).getSheets();
      if ( checkSht1.length == 1 ) { 

        if (checkSht1[0].getRange(1, 1).getValue() == "BARCODE") {

          sht.setTrashed(true);


        }
      }
    }
  }
}

非常感谢您阅读所有内容,我已经对此坚持了太久了。我已经尝试了许多不同的方法,但是总是得到相同的结果(除非我手动开始一个,然后在完成第一个之后手动另一个)。希望代码不会太混乱,我是编码的新手:)

库珀

您是否在第一个函数的末尾尝试了SpreadsheetApp.flush?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章