0

On repeated imports into the same sheet, most formatting is preserved (e.g. colors) but some is not (e.g. setting a column to % format). How can I preserve all formatting already in the sheet prior to repeated csv imports, e.g. a script as follows that repeatedly updates the sheet (where "file" is a csv file on a Google Drive):

var content = file.getBlob().getDataAsString();  # csv file on a Google Drive
var csvData = Utilities.parseCsv(content);
current_sheet.clearContents();
current_sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
Kim Miller
  • 886
  • 8
  • 11

2 Answers2

1

SOLVED: With the help of this post: Copy value and format from a sheet to a new google Spreadsheet document?

The first and last lines are the solution:

var sNF = current_sheet.getDataRange().getNumberFormats();

var content = file.getBlob().getDataAsString();  # csv file on a Google Drive
var csvData = Utilities.parseCsv(content);
current_sheet.clearContents();
current_sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);

current_sheet.getDataRange().setNumberFormats(sNF)
Kim Miller
  • 886
  • 8
  • 11
0

I just did a quick test with the script below and the cells formatting was preserved.

function importCSVFromWeb() {
  // Provide the full URL of the CSV file.
  var csvUrl = "https://query1.finance.yahoo.com/v7/finance/download/MSFT?period1=1577806579&period2=1609428979&interval=1d&events=history&includeAdjustedClose=true";
  var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
  var csvData = Utilities.parseCsv(csvContent);

  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.clearContents();
  sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}

There is a slight difference in the way I fetched the data

JohnA
  • 1,058
  • 6
  • 12
  • While I like the general approach, `getContentText()` does not seem available to my fetch method, which is `file.getBlob().getDataAsString();` – Kim Miller Jun 25 '21 at 21:51