I am working on a google script to import CSV files from web urls to individual sheets in a google sheet. I would like to have it clear the contents of certain columns before importing the new info. I had had trouble getting the script to clear contents prior to importing. I have also had in include part of one CSV along with another on a sheet. I think I need to add something to the script between CSV files. I also need something added to clear contents prior to importing. I don't want to just clear the sheet because there are formulas that need to remain. I also don't want to use the Google IMPORTDATA function because it is unreliable.
Here is my current script (URLs removed):
function importCSVFromWeb() {
var csvUrl = "http://csvurlhere";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var csvData = Utilities.parseCsv(csvContent);
var ss = SpreadsheetApp.openByUrl('spreadsheeturlhere');
var sheet = SpreadsheetApp.getActiveSheet();
var ss = sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
var csvUrl = "http://csvurlhere";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var csvData = Utilities.parseCsv(csvContent);
var sheet = SpreadsheetApp.getActive().getSheetByName('RentPaid');
var ss = sheet.getRange(3, 3, csvData.length, csvData[0].length).setValues(csvData);
var csvUrl = "http://csvurlhere";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var csvData = Utilities.parseCsv(csvContent);
var sheet = SpreadsheetApp.getActive().getSheetByName('Tenants');
var ss = sheet.getRange(1, 2, csvData.length, csvData[0].length).setValues(csvData);
var csvUrl = "http://csvurlhere";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var csvData = Utilities.parseCsv(csvContent);
var sheet = SpreadsheetApp.getActive().getSheetByName('Owners');
var ss = sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
To clear the contents of a sheet or a range of cells within a sheet, you can use
sheet.clearContents()
orrange.clearContent()
, which will remove only values & leave your formatting & formulas in tact.I note that your line
var ss = SpreadsheetApp.openByUrl('spreadsheeturlhere');
does nothing as you subsequently redeclare thess
variable. If the script is bound to a spreadsheet, you don't need this line as calls togetActive()
&getActiveSheet()
will give you a reference to the host spreadsheet. Your calls toSpreadsheetApp.getActive().getSheetByName()
are returning references to the host spreadsheet anyway, not the one you open by URL.I would also consider changing your function to accept the CSV source URLs, sheet names & cell anchors as parameters so that the code is easier to maintain. e.g.