用于从文件列表中导入CSV文件的Google脚本

时间:2014-02-07 10:03:17

标签: javascript google-apps-script

我正在尝试将数据从csv文件导入Google表格。以下代码运行良好,但它依赖于确定要​​导入的文件的UI。我想更改此设置,让用户从给定Google文件夹中的文件列表中进行选择。执行这项工作的代码是由Ben Nadel提供的。

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

  ss.addMenu("User Functions", menuEntries);
}



function importFromCSV() {
//from here
  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 folderName = DocsList.getFolder('SBV Imported EE Data');
  var fileName = "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.getActiveSheet();
  for (var i = 0; i < csvData.length; i++) {
    sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
  }
}

// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// 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 );
}

1 个答案:

答案 0 :(得分:0)

一些小修改应该可以解决问题:

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

  ss.addMenu("User Functions", menuEntries);
}


function showImportWindow(){
  // https://developers.google.com/drive/web/search-parameters
  // http://fr.wikipedia.org/wiki/Type_MIME
  var filesIterator = DriveApp.searchFiles("mimeType = 'text/csv' and 'FOLDER_ID' in parents");
  // don't forget to change FOLDER_ID or to suppress "and 'FOLDER_ID' in parents""

  var fileList = [];
  while(filesIterator.hasNext()){
    var file = filesIterator.next();
    fileList.push([file.getId(),file.getName()]);
    Utilities.sleep(40); // longer better
  }
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var app = UiApp.createApplication();
  var list = app.createListBox().setId("list").setName("list");
  for(var i in fileList){
    list.addItem(fileList[i][1], fileList[i][0]);
  }

  var panel = app.createVerticalPanel();
  panel.add(app.createLabel("select a file")).add(list).add(app.createButton("submit").addClickHandler(app.createServerHandler("importBaseData").addCallbackElement(list)));
  app.add(app.createFormPanel().add(panel));
  ss.show(app);
}


//function importFromCSV(e) {
////from here
//  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){
  Logger.log(JSON.stringify(e));
  Logger.log(e.parameter.list);
  var csvFile = DriveApp.getFileById(e.parameter.list).getBlob().getDataAsString();
//  var folderName = DocsList.getFolder('SBV Imported EE Data');
//  var fileName = "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.getActiveSheet();
  for (var i = 0; i < csvData.length; i++) {
    sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
  }
}

// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// 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 );
}