2013-09-23 2 views
0

У меня есть сценарий, который импортирует данные из файла csv после вставки имени файла через пользовательский интерфейс. Все работает на 100%, файл находится и данные импортируются, как ожидалось. Однако приложение не закрывается, и всплывающий интерфейс пользователя остается активным на экране.Скриншот приложения Google Apps закрыть приложение после выполнения

Мой сценарий выглядит следующим образом:

function onOpen() { 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var menuEntries = [ 
        {name: "Import Employee Base Data", functionName: "importFromBaseCSV"}, 
        ]; 
    ss.addMenu("User Functions", menuEntries); 
} 

//IMPORT BASE DATA FROM CSV 

function importFromBaseCSV() { 

    var ss = SpreadsheetApp.getActiveSpreadsheet(); 

    var importBaseDataApp = UiApp.createApplication().setTitle('Import BASE Data').setHeight(120).setWidth(350); 

    var importBaseDataGrid = importBaseDataApp.createGrid(3, 2); 
    importBaseDataGrid.setWidget(0, 0, importBaseDataApp.createLabel('Enter the File Date: ')); 
    importBaseDataGrid.setWidget(0, 1, importBaseDataApp.createTextBox().setName('baseDataFilename').setFocus(true).setWidth(150)); 
    importBaseDataGrid.setWidget(1, 0, importBaseDataApp.createLabel('e.g. 23092013')); 
    importBaseDataGrid.setWidget(2, 0, importBaseDataApp.createLabel('')); 

    var importBaseDataPanel = importBaseDataApp.createVerticalPanel(); 
    importBaseDataPanel.add(importBaseDataGrid); 

    var importButton = importBaseDataApp.createButton('Import'); 
    var importHandler = importBaseDataApp.createServerHandler('importBaseData'); 
    importHandler.addCallbackElement(importBaseDataGrid); 
    importButton.addClickHandler(importHandler); 

    importBaseDataPanel.add(importButton); 
    importBaseDataApp.add(importBaseDataPanel); 
    ss.show(importBaseDataApp); 

} 

function importBaseData(e){ 

    var fileName = "C BS BASE " + e.parameter.baseDataFilename + ".csv"; 
    var files = DocsList.getFiles(); 
    var csvFile = ""; 

    for (var i = 0; i < files.length; i++) { 
    if (files[i].getName() == fileName) { 
     csvFile = files[i].getContentAsString(); 
     break; 
    } 
    } 
    var csvData = CSVToArray(csvFile, ","); 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var sheet = ss.getSheetByName("Imported Base Data"); 
    for (var i = 0; i < csvData.length; i++) { 
    sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i])); 
    } 
} 

// This will parse a delimited string into an array of 
// arrays. The default delimiter is the comma, but this 
// can be overriden in the second argument. 

function CSVToArray(strData, strDelimiter){ 
    // Check to see if the delimiter is defined. If not, 
    // then default to comma. 
    strDelimiter = (strDelimiter || ","); 

    // Create a regular expression to parse the CSV values. 
    var objPattern = new RegExp(
    (
     // Delimiters. 
     "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + 

     // Quoted fields. 
     "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + 

     // Standard fields. 
     "([^\"\\" + strDelimiter + "\\r\\n]*))" 
    ), 
    "gi" 
); 


    // Create an array to hold our data. Give the array 
    // a default empty first row. 
    var arrData = [[]]; 

    // Create an array to hold our individual pattern 
    // matching groups. 
    var arrMatches = null; 


    // Keep looping over the regular expression matches 
    // until we can no longer find a match. 
    while (arrMatches = objPattern.exec(strData)){ 

    // Get the delimiter that was found. 
    var strMatchedDelimiter = arrMatches[ 1 ]; 

    // Check to see if the given delimiter has a length 
    // (is not the start of string) and if it matches 
    // field delimiter. If id does not, then we know 
    // that this delimiter is a row delimiter. 
    if (
     strMatchedDelimiter.length && 
     (strMatchedDelimiter != strDelimiter) 
    ){ 

     // Since we have reached a new row of data, 
     // add an empty row to our data array. 
     arrData.push([]); 

    } 


    // Now that we have our delimiter out of the way, 
    // let's check to see which kind of value we 
    // captured (quoted or unquoted). 
    if (arrMatches[ 2 ]){ 

     // We found a quoted value. When we capture 
     // this value, unescape any double quotes. 
     var strMatchedValue = arrMatches[ 2 ].replace(
     new RegExp("\"\"", "g"), 
     "\"" 
    ); 

    } else { 

     // We found a non-quoted value. 
     var strMatchedValue = arrMatches[ 3 ]; 

    } 


    // Now that we have our value string, let's add 
    // it to the data array. 
    arrData[ arrData.length - 1 ].push(strMatchedValue); 
    } 

    SpreadsheetApp.getActiveSpreadsheet().toast("...Completed", "Import Employee Base Data:", 3); 

    // Return the parsed data. 
    return(arrData); 

    var importBaseDataApp = UiApp.getActiveApplication(); 
    importBaseDataApp.close(); 
    return importBaseDataApp; 

} 

Может кто-нибудь помочь?

ответ

0

Я просто посмотрел на него быстро, но попробуйте это. Я переместил «Toast» и «Close» в функцию, вызываемую щелчком мыши. Вы хотите контролировать Ui в своей вызывающей функции, гораздо более плавную. Иногда вам может повезти, и они закрывают или обновляют вызов в другой вызываемой функции.

function importBaseData(e){ 

    var fileName = "C BS BASE " + e.parameter.baseDataFilename + ".csv"; 
    var files = DocsList.getFiles(); 
    var csvFile = ""; 

    for (var i = 0; i < files.length; i++) { 
    if (files[i].getName() == fileName) { 
     csvFile = files[i].getContentAsString(); 
     break; 
    } 
    } 
    var csvData = CSVToArray(csvFile, ","); 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var sheet = ss.getSheetByName("Imported Base Data"); 
    for (var i = 0; i < csvData.length; i++) { 
    sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i])); 
    } 
    SpreadsheetApp.getActiveSpreadsheet().toast("...Completed", "Import Employee Base Data:", 3); 

    var importBaseDataApp = UiApp.getActiveApplication(); 
    importBaseDataApp.close(); 
    return importBaseDataApp; 
} 

// This will parse a delimited string into an array of 
// arrays. The default delimiter is the comma, but this 
// can be overriden in the second argument. 

function CSVToArray(strData, strDelimiter){ 
    // Check to see if the delimiter is defined. If not, 
    // then default to comma. 
    strDelimiter = (strDelimiter || ","); 

    // Create a regular expression to parse the CSV values. 
    var objPattern = new RegExp(
    (
     // Delimiters. 
     "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + 

     // Quoted fields. 
     "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + 

     // Standard fields. 
     "([^\"\\" + strDelimiter + "\\r\\n]*))" 
    ), 
    "gi" 
); 


    // Create an array to hold our data. Give the array 
    // a default empty first row. 
    var arrData = [[]]; 

    // Create an array to hold our individual pattern 
    // matching groups. 
    var arrMatches = null; 


    // Keep looping over the regular expression matches 
    // until we can no longer find a match. 
    while (arrMatches = objPattern.exec(strData)){ 

    // Get the delimiter that was found. 
    var strMatchedDelimiter = arrMatches[ 1 ]; 

    // Check to see if the given delimiter has a length 
    // (is not the start of string) and if it matches 
    // field delimiter. If id does not, then we know 
    // that this delimiter is a row delimiter. 
    if (
     strMatchedDelimiter.length && 
     (strMatchedDelimiter != strDelimiter) 
    ){ 

     // Since we have reached a new row of data, 
     // add an empty row to our data array. 
     arrData.push([]); 

    } 


    // Now that we have our delimiter out of the way, 
    // let's check to see which kind of value we 
    // captured (quoted or unquoted). 
    if (arrMatches[ 2 ]){ 

     // We found a quoted value. When we capture 
     // this value, unescape any double quotes. 
     var strMatchedValue = arrMatches[ 2 ].replace(
     new RegExp("\"\"", "g"), 
     "\"" 
    ); 

    } else { 

     // We found a non-quoted value. 
     var strMatchedValue = arrMatches[ 3 ]; 

    } 


    // Now that we have our value string, let's add 
    // it to the data array. 
    arrData[ arrData.length - 1 ].push(strMatchedValue); 
    } 
    // Return the parsed data. 
    return(arrData); 

} 
+0

Большое спасибо. Это сработало и, конечно, имеет смысл. Большое спасибо за помощь. –

Смежные вопросы