Filter CVS before importing to Google Spreadsheet

本秂侑毒 提交于 2021-01-29 07:40:46

问题


I have a Script in a Google Spreadsheet, the script downloads a zipped CSV from an URL and then import it to the spreadsheet. Actually, the CVS is too big and I don't need all the data from it. My question is, How can I filter the data before importing it to the spreadsheet? For example filter Column A with X value.

This is the code I have so far:

function descargarzip() 
{
var urldescarga = "http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip"
var url = urldescarga
var zipblob = UrlFetchApp.fetch(url).getBlob(); 
zipblob.setContentTypeFromExtension();
var unzipblob = Utilities.unzip(zipblob); 
var unzipstr=unzipblob[0].getDataAsString();
var csv = Utilities.parseCsv(unzipstr);

var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
ss.getRange(1, 1, csv.length, csv[0].length).setValues(csv);
}

Thank you in advance!


回答1:


Try this:

function descargarzip() {
  var urldescarga = "http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip"
  var url = urldescarga
  var zipblob = UrlFetchApp.fetch(url).getBlob(); 
  zipblob.setContentTypeFromExtension();
  var unzipblob = Utilities.unzip(zipblob); 
  var unzipstr=unzipblob[0].getDataAsString();
  var csv = Utilities.parseCsv(unzipstr);
  var x = 'You enter the contents x';
  csv.forEach(function(r,i){
    if(r[0]==x) {
      r[0]='';//You have to put something back in there because the csv has to be a rectangular array for setValues();
    }
  });//You could remove an entire line or an entire column
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  ss.getRange(1, 1, csv.length, csv[0].length).setValues(csv);
}

If @TheMaster is correct then try this:

function descargarzip() {
  var urldescarga = "http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip"
  var url = urldescarga
  var zipblob = UrlFetchApp.fetch(url).getBlob(); 
  zipblob.setContentTypeFromExtension();
  var unzipblob = Utilities.unzip(zipblob); 
  var unzipstr=unzipblob[0].getDataAsString();
  var csv = Utilities.parseCsv(unzipstr);
  var x = 'You enter the contents x';
  var d=0;
  //I tested this on some of my data and I believe it works
  for(var i=0;(i-d)<csv.length;i++) {
    if(csv[i-d][0]==x) {
      csv.splice(i-d++,1);//I think this is correct but I could be wrong in here because I mostly use this approach for deleting rows not portions of the array.  So if you have problems the please share your csv data and I will debug it.
    }
  }
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  ss.getRange(1, 1, csv.length, csv[0].length).setValues(csv);
}


来源:https://stackoverflow.com/questions/61256412/filter-cvs-before-importing-to-google-spreadsheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!