OK. It seems you need push a CSV data to the current sheet. You can use Advanced Sheets Service
var CSV_FILE_ID = '1G9eI5bj_jYQz_a_mk4t5mmLJsgwOpP8q'; // Your CSV file or data
var SHEETID = '0';
/**
* User action. Import the CSV file
*/
function userActionImportFromCSV() {
var res = importFromCSV_(
CSV_FILE_ID,
SpreadsheetApp.getActive().getId(),
SHEETID
);
Logger.log(res);
}
/**
* Imports the CSV file to the Sheet
* @param {string} csvId CSV file Id
* @param {string} spreadsheetId Spreadsheet Id
* @param {string} sheetId Sheet Uid
* @return {any}
*/
function importFromCSV_(csvId, spreadsheetId, sheetId) {
// Get CSV data
var data = DriveApp.getFileById(csvId)
.getBlob()
.getDataAsString();
// Clear the Sheet
var updateCellsRequest = Sheets.newUpdateCellsRequest();
updateCellsRequest.fields = 'userEnteredValue';
updateCellsRequest.range = { sheetId: sheetId };
batchUpdateSpreadsheet_(
{
updateCells: updateCellsRequest,
},
spreadsheetId
);
// Paste the data
var pasteDataRequest = Sheets.newPasteDataRequest();
pasteDataRequest.coordinate = {
sheetId: SHEETID,
rowIndex: 0,
columnIndex: 0,
};
pasteDataRequest.data = data;
pasteDataRequest.type = SpreadsheetApp.CopyPasteType.PASTE_VALUES;
pasteDataRequest.delimiter = ',';
var batchUpdateSpreadsheetResponse = batchUpdateSpreadsheet_(
{
pasteData: pasteDataRequest,
},
spreadsheetId
);
return batchUpdateSpreadsheetResponse;
}
/**
*
* @param {object} request Request object
* @param {string} spreadsheetId Spreadsheet Id
* @return {object} BatchUpdateSpreadsheetResponse
*/
function batchUpdateSpreadsheet_(request, spreadsheetId) {
var resource = {
requests: [],
};
resource.requests.push(request);
var batchUpdateSpreadsheetResponse = Sheets.Spreadsheets.batchUpdate(
resource,
spreadsheetId
);
return batchUpdateSpreadsheetResponse;
}
If some one need export to CSV also
So if it is a really a real file then you can
function overWriteFileSample() {
const file = DriveApp.getFileById('ABCD1234'); // Your CSV file
const content = new Date().toISOString();
file.setContent(content);
}
If it's a Sheet. Then before all you have to export the file to CSV. After that you can setContent
.
For sample this works fine
function run(){
exportToCSV_('ABCD1234', spreadsheetId, sheetId)
}
/**
*
* @param {string} csvId
* @param {string} spreadsheetId
* @param {string | number} sheetId
*/
function exportToCSV_(csvId, spreadsheetId, sheetId) {
var url = Utilities.formatString(
'https://docs.google.com/spreadsheets/export?id=%s&exportFormat=csv&gid=%s',
spreadsheetId,
sheetId
);
var data = UrlFetchApp.fetch(url, {
headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
}).getBlob();
DriveApp.getFileById(csvId).setContent(data.getDataAsString());
}
Based on the snippet sheets/export-import-to-csv