Javascript 访问、解析和写入.csv数据-谷歌应用程序脚本

Javascript 访问、解析和写入.csv数据-谷歌应用程序脚本,javascript,parsing,csv,google-apps-script,Javascript,Parsing,Csv,Google Apps Script,我在谷歌电子表格中运行javascript。我正试图上传一个.cs文件,对其进行解析,然后将其写入电子表格。(这是在将.csv数据写入电子表格之前能够对其进行操作的初步步骤)。.csv已成功上载到Google文档列表,但我无法将其写入电子表格。我在测试天气时遇到问题,或者我的脚本是否实际获取了.csv数据,因此我可以对其进行分析。我的脚本包括在下面。我真的很感激任何建议。我尝试了几种变体,当前的变体抛出了一个“csvFile is undefined”错误。我不知道var files=DocsL

我在谷歌电子表格中运行javascript。我正试图上传一个.cs文件,对其进行解析,然后将其写入电子表格。(这是在将.csv数据写入电子表格之前能够对其进行操作的初步步骤)。.csv已成功上载到Google文档列表,但我无法将其写入电子表格。我在测试天气时遇到问题,或者我的脚本是否实际获取了.csv数据,因此我可以对其进行分析。我的脚本包括在下面。我真的很感激任何建议。我尝试了几种变体,当前的变体抛出了一个“csvFile is undefined”错误。我不知道
var files=DocsList.getFiles(fileBlob);var csvFile=“”;csvFile=files.getContentAsString()正在工作。我如何测试这个?运行google调试器总是会导致所有变量都未定义,因为没有用户上载文件。谢谢你的关注-杰米

// Retrieves all the rows in the active spreadsheet that contain data and logs the
// values for each row.
function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    Logger.log(row);
  }
};


//Adds a custom menu to the active spreadsheet, containing a single menu item
//for invoking the readRows() function specified above.

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = 
      [ {name:"Read Data", functionName:"readRows"},
        {name:"Upload DSR", functionName:"doGet"} ];

  sheet.addMenu("Du-par's", entries);
};


// Create Menu to Locate .CSV
 function doGet(e) {

 var app = UiApp.createApplication().setTitle("Upload DSR");
   var formContent = app.createVerticalPanel();
   formContent.add(app.createFileUpload().setName('thefile'));
   formContent.add(app.createSubmitButton("Submit DSR"));
   var form = app.createFormPanel();
   form.add(formContent);
   app.add(form);
   SpreadsheetApp.getActive().show(app);
   return app;
   }

// Upload .CSV to Cloud
 function doPost(e) {

// data returned is a blob for FileUpload widget
   var fileBlob = e.parameter.thefile;
   var doc = DocsList.createFile(fileBlob); 

   var app = UiApp.getActiveApplication();

  // Display a confirmation message
     var label = app.createLabel('file uploaded successfully');
   app.add(label);
   SpreadsheetApp.getActive().show(app);

     var files = DocsList.getFiles(fileBlob);
     var csvFile = "";
     csvFile = files.getContentAsString();
     }

  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]));
  }


 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 );

  // Using active sheet here, but you can pull up a sheet in several other ways as well
  //SpreadsheetApp.getActiveSheet()
    //            .getRange( 1, 1, values.length, values[0].length )
      //          .setValues(values);
} 
//检索活动电子表格中包含数据和日志的所有行
//每行的值。
函数readRows(){
var sheet=SpreadsheetApp.getActiveSheet();
var rows=sheet.getDataRange();
var numRows=rows.getNumRows();
var values=rows.getValues();

对于(var i=0;i,您的代码中有一些错误。下面是一个工作版本,在我修改的行上有注释

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = 
      [ {name:"Read Data", functionName:"readRows"},
        {name:"Upload DSR", functionName:"doGet"} ];

  sheet.addMenu("Du-par's", entries);
};

//Adds a custom menu to the active spreadsheet, containing a single menu item
//for invoking the readRows() function specified above.

// Create Menu to Locate .CSV
function doGet(e) {

  var app = UiApp.createApplication().setTitle("Upload DSR");
  var formContent = app.createVerticalPanel();
  formContent.add(app.createFileUpload().setName('thefile'));
  formContent.add(app.createSubmitButton("Submit DSR"));
  var form = app.createFormPanel();
  form.add(formContent);
  app.add(form);
  SpreadsheetApp.getActive().show(app);
  return app;
}

// Upload .CSV to Cloud
function doPost(e) {
  var app = UiApp.getActiveApplication();  
  // data returned is a blob for FileUpload widget
  var fileBlob = e.parameter.thefile;
  var doc = DocsList.createFile(fileBlob); 
  // Display a confirmation message
  var label = app.createLabel('file uploaded successfully');
  app.add(label);  
  var files = DocsList.getFileById(doc.getId());// to get the document's data back you need to use the right method... fileBlob was not the right argument
  var csvFile = ""; // this part was not inside the doPost function, it wasn't included in any function thus trying to run each time any function is called, includind onOpen()... beware the {}...
  csvFile = files.getContentAsString();
  var csvData = CSVToArray(csvFile, ",");
  Logger.log(csvData)
  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]));
  }
  return app;// you don't need to re-call the show method, just return the active app to update the UI
}


function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    Logger.log(row);
  }
};



function CSVToArray( strData, strDelimiter ){
Logger.log(strData);
  // 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 );

  // Using active sheet here, but you can pull up a sheet in several other ways as well
  //SpreadsheetApp.getActiveSheet()
    //            .getRange( 1, 1, values.length, values[0].length )
      //          .setValues(values);
} 

您的代码中有一些错误。这是一个工作版本,在我修改的行上有注释

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = 
      [ {name:"Read Data", functionName:"readRows"},
        {name:"Upload DSR", functionName:"doGet"} ];

  sheet.addMenu("Du-par's", entries);
};

//Adds a custom menu to the active spreadsheet, containing a single menu item
//for invoking the readRows() function specified above.

// Create Menu to Locate .CSV
function doGet(e) {

  var app = UiApp.createApplication().setTitle("Upload DSR");
  var formContent = app.createVerticalPanel();
  formContent.add(app.createFileUpload().setName('thefile'));
  formContent.add(app.createSubmitButton("Submit DSR"));
  var form = app.createFormPanel();
  form.add(formContent);
  app.add(form);
  SpreadsheetApp.getActive().show(app);
  return app;
}

// Upload .CSV to Cloud
function doPost(e) {
  var app = UiApp.getActiveApplication();  
  // data returned is a blob for FileUpload widget
  var fileBlob = e.parameter.thefile;
  var doc = DocsList.createFile(fileBlob); 
  // Display a confirmation message
  var label = app.createLabel('file uploaded successfully');
  app.add(label);  
  var files = DocsList.getFileById(doc.getId());// to get the document's data back you need to use the right method... fileBlob was not the right argument
  var csvFile = ""; // this part was not inside the doPost function, it wasn't included in any function thus trying to run each time any function is called, includind onOpen()... beware the {}...
  csvFile = files.getContentAsString();
  var csvData = CSVToArray(csvFile, ",");
  Logger.log(csvData)
  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]));
  }
  return app;// you don't need to re-call the show method, just return the active app to update the UI
}


function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    Logger.log(row);
  }
};



function CSVToArray( strData, strDelimiter ){
Logger.log(strData);
  // 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 );

  // Using active sheet here, but you can pull up a sheet in several other ways as well
  //SpreadsheetApp.getActiveSheet()
    //            .getRange( 1, 1, values.length, values[0].length )
      //          .setValues(values);
} 

仅供参考,这些天你可以使用“Utilities.parseCsv'()而不必滚动你自己的CSVToArray功能。仅供参考,这些天你可以使用“Utilities.parseCsv'()而不必滚动你自己的CSVToArray功能。我投票结束这个问题,因为它是关于使用不推荐的谷歌应用程序脚本服务(UiApp和DocList)我投票结束这个问题,因为它是关于使用不推荐的谷歌应用脚本服务(UiApp和DocList)