Replace NULL values when importing CSV in a Spreadsheet - csv

With this code I can import from a CSV to my sheet.
Now, I would avoid to display NULL values in the cells and replace them with an empty value.
What I could add to the code I use?
function testf() {
var response = UrlFetchApp.fetch("https://xxx.csv");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dest = ss.getActiveSheet();
SpreadsheetApp.flush();
var req = { pasteData: { data: response.getContentText(), delimiter: ",", coordinate: { sheetId: dest.getSheetId() } } };
Sheets.Spreadsheets.batchUpdate({requests: [req]}, ss.getId());
}

From Now, I would avoid to display NULL values in the cells and replace them with an empty value., if you want to replace NULL in the cells with the empty value, how about the following modification?
Modified script:
function testf() {
var response = UrlFetchApp.fetch("https://xxx.csv");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dest = ss.getActiveSheet();
SpreadsheetApp.flush();
var sheetId = dest.getSheetId();
var reqs = [
{ pasteData: { data: response.getContentText(), delimiter: ",", coordinate: { sheetId } } },
{ findReplace: { find: "NULL", replacement: "", sheetId } }
];
Sheets.Spreadsheets.batchUpdate({ requests: reqs }, ss.getId());
}
In this modification, after the CSV was inserted, the value of NULL in the cells is replaced with "" using the batchUpdate method. In this case, this request can be run by one API call.
In your script, SpreadsheetApp.flush() might not be required to be used.
Reference:
FindReplaceRequest

Related

Sheets API: Append Row with hidden columns

I have a "appendRow" function for insert rows in the Google sheet called "Data", and this sheet has a column called "Id" (**A** column) which is hidden by client request.
function appendRow() {
var spreadsheetId = "SPREADSHEET_ID";
var range = "Data!A2:C";
var resource = {
values: [
["1", "James", "jam10#gmail.com"]
]
};
Sheets.Spreadsheets.Values.append(resource, spreadsheetId, range, {
valueInputOption: "USER_ENTERED"
});
}
However, when I execute this function, the result is not the expected, as seen in the image.
I appreciate any information, idea or solution that can help me to resolve this incident. Regards.
function appendRow() {
const ss = SpreadsheetApp.openById("SS_ID");
const sh = ss.getSheetByName('Data');
sh.appendRow(["1", "James", "jam10#gmail.com"]);
}
//row must be 2d array
function appendRows(rows) {
var spreadsheetId = "SPREADSHEET_ID";
const ss = SpreadsheetApp.openById("SSID");
const sh = ss.getSheetByName('Data');
sh.getRange(sh.getLastRow() + 1, 1, rows.length, rows[0].length).setValues(rows);
}

Google Sheets App Script Export to CSV selected Columns

I have this google sheets script which will export my current google sheet to a CSV format in my drive folder.
I tried to select column Index. Ex: columnIndex: 1,2,6,10 But without success, its still export the full data sheet
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('CSV')
.addItem('Export to the file', 'userActionExportToCSV')
.addToUi();
}
// https://drive.google.com/file/d/1111111111/view?usp=sharing
var CSV_FILE_ID = '11111111111__8SC0RDV';
var SHEETID = '0';
function userActionExportToCSV() {
var res = exportToCSV_(
CSV_FILE_ID,
SpreadsheetApp.getActive().getId(),
SpreadsheetApp.getActiveSheet().getSheetId()
);
Logger.log(res);
}
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
);
var pasteDataRequest = Sheets.newPasteDataRequest();
pasteDataRequest.coordinate = {
sheetId: SpreadsheetApp.getActiveSheet().getSheetId(),
rowIndex: 0,
columnIndex: 0,
};
pasteDataRequest.data = data;
pasteDataRequest.type = SpreadsheetApp.CopyPasteType.PASTE_VALUES;
pasteDataRequest.delimiter = ',';
var batchUpdateSpreadsheetResponse = batchUpdateSpreadsheet_(
{
pasteData: pasteDataRequest,
},
spreadsheetId
);
return batchUpdateSpreadsheetResponse;
}
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() }, muteHttpExceptions: true
}).getBlob();
DriveApp.getFileById(csvId).setContent(data.getDataAsString());
}
function batchUpdateSpreadsheet_(request, spreadsheetId) {
var resource = {
requests: [],
};
resource.requests.push(request);
var batchUpdateSpreadsheetResponse = Sheets.Spreadsheets.batchUpdate(
resource,
spreadsheetId
);
return batchUpdateSpreadsheetResponse;
}
I would like to only export some selected columns. By example columns 1,2,6,10.
How I can modify this script to only export the selected columns in my CSV file saved on my Google Drive?

How to append an html table to a sheet

This script sends the data content of an html table to a Google Sheet.
But I now need it to append the data to the next available row.
I've used appendRow() in many cases, but I'm not sure of the syntax in this particular case.
function pasteRequisicaoHtml(table) {
var ss = SpreadsheetApp.openById("1J_7GZ1C7pgHuRsdfsdfsdfsdf");
var sheet = ss.getSheetByName('Sheet5').getSheetId();
var req = {
requests: [
{
pasteData: {
html: true,
data: table,
coordinate: {
sheetId: sheet,
rowIndex: 2,
columnIndex: 0,
},
},
},
],
};
Sheets.Spreadsheets.batchUpdate(req, ss.getId());
}
You want to put a HTML table to "the next available row" using Sheets API with Google Apps Script as appending.
If my understanding is correct, how about this answer?
Modification point:
In your case, you can use both Sheets API and Spreadsheet service. Using this, in order to append the table using Sheets API, you can use getLastRow() of Spreadsheet service. And please use the value retrieved by getLastRow() to rowIndex.
When this is reflected to your script, it becomes as follows.
Modified script:
function pasteRequisicaoHtml(table) {
var ss = SpreadsheetApp.openById("1J_7GZ1C7pgHuRsdfsdfsdfsdf");
var sheet = ss.getSheetByName('Sheet5'); // Modified
var req = {
requests: [{
pasteData: {
html: true,
data: table,
coordinate: {
sheetId: sheet.getSheetId(), // Modified
rowIndex: sheet.getLastRow(), // Modified
columnIndex: 0,
},
},
}, ],
};
Sheets.Spreadsheets.batchUpdate(req, ss.getId());
}
References:
getLastRow()
GridCoordinate
Added:
In this sample script, the header row is deleted after the table is append. In this case, it supposes that the header row is one row.
function pasteRequisicaoHtml(table) {
var ss = SpreadsheetApp.openById("1J_7GZ1C7pgHuRsdfsdfsdfsdf");
var sheet = ss.getSheetByName('Sheet5'); // Modified
var lastRow = sheet.getLastRow(); // Added
var req = {
requests: [{
pasteData: {
html: true,
data: table,
coordinate: {
sheetId: sheet.getSheetId(), // Modified
rowIndex: lastRow, // Modified
columnIndex: 0,
},
},
}, ],
};
Sheets.Spreadsheets.batchUpdate(req, ss.getId());
sheet.deleteRow(lastRow + 1); // Added
}

Google sheets - Json to Sheet

I'm using this Google App script
// Reference: https://www.labnol.org/code/20068-blogger-api-with-google-apps-script
function bloggerAPI() {
var api = "https://www.googleapis.com/blogger/v3/users/self/blogs";
var headers = {
"Authorization": "Bearer " + getService().getAccessToken()
};
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(api, options);
var json = JSON.parse(response.getContentText());
for (var i in json.items) {
Logger.log("[%s] %s %s", json.items[i].id, json.items[i].name, json.items[i].url);
}
}
How can I import the values that are in the Logger.log into my sheet.
You have to change the Logger.log() for appendRow().
In your case you have to set the sheet you want to insert the values:
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Gets the Active Spreadsheet
var ss = SpreadsheetApp.openById("ID OF THE SPREADSHEET"); // Alternative way of getting a Spreadsheet
var sheet = ss.getSheets()[0]; // Gets the first sheet
var sheet = ss.getSheets().getSheetByName("Sheet4"); // Gets the sheet with the name Sheet4
Once you have the Spreadsheet you want, inside the for loop, you insert the values:
sheet.appendRow([json.items[i].id, json.items[i].name, json.items[i].url]);

How do I use Sheets.Spreadsheets.getByDataFilter from app script for a filter view that is created in spreadsheet?

I am seeking help with the following case
I have a spreadsheet, and it contains few filter views - f1, f2, ...
I have an app script associated with the spreadsheet. I have enabled Resources > Advanced Google Services to access the Sheets API v4.
Currently, I access that data as
var fruits = Sheets.Spreadsheets.Values.get("1YBPXShvssFpTI-5dPSsy_N_iEVaeHezdxymsdxpTy6w", "Fruits!A:B").values;
And I get the corresponding data back.
I would now, like to only get the data that is used by the filter view, so that I do not bring the entire data which is not necessary and slows down the processing.
I saw that there is something called Sheets.Spreadsheets.getByDataFilter(resource, spreadsheetId), but I am not sure how to create the resource object.
Given my filters, and knowing the spreadsheet Id, how do I only fetch the data based on the filter names that I know?
UPDATE
My latest attempt looks like
var ss = SpreadsheetApp.getActiveSpreadsheet();
function getUnpostedItems() {
Logger.log("This function will prioritize the new items that are added into the inventory");
var sheet = ss.getSheetByName("Items");
var filterSettings = {};
filterSettings.criteria = {};
var condition = {
"condition": {
"type": "LESS_THAN",
"values": [
{ "userEnteredValue": "=NOW()-30" }
]
}
}
filterSettings['criteria'][1] = {
'condition': condition
};
var filterSettings = {
range: {
sheetId: sheet.getSheetId(),
},
}
var req = {
"setBasicFilter": {
"filter": filterSettings
}
}
// var items = Sheets.Spreadsheets.batchUpdate({'requests': [req]}, ss.getId());
var items = ss.getRange("Items!A:B").getValues()
// var items1 = Sheets.Spreadsheets.Values.get("1YBPXShvssFpTI-5dPSsy_N_iEVaeHezdxymsdxpTy6c", "Items!A:B").values
Logger.log("Found items:" + items.length);
return [];
}
But no luck so far!
As per #tanaike's help, I was able to get the following working
function getUnpostedItems() {
Logger.log("This function will prioritize the new items that are added into the inventory");
// var ss = SpreadsheetApp.getActiveSpreadsheet(); // Added
var sheet = ss.getSheetByName("Items"); // Modified
var values = sheet.getDataRange().getValues();
Logger.log("VALUES "+values.length);
//var newCriteria = SpreadsheetApp.newFilterCriteria().whenDateBefore(new Date()).build();
var newCriteria = SpreadsheetApp.newFilterCriteria().whenDateBefore(subDaysFromDate(new Date(), 30)).build();
var range = sheet.getFilter().setColumnFilterCriteria(1, newCriteria).getRange(); //The 1-indexed position of the column.
// values = range.getValues();
// I added below script.
var res = Sheets.Spreadsheets.get(ss.getId(), {
ranges: ["Items"], // <--- Please set the sheet name.
fields: "sheets/data"
});
var values = res.sheets[0].data[0].rowMetadata.reduce(function(ar, e, i) {
if (!e.hiddenByFilter && res.sheets[0].data[0].rowData[i]) {
ar.push(
res.sheets[0].data[0].rowData[i].values.map(function(col) {
return col.userEnteredValue[Object.keys(col.userEnteredValue)[0]];
})
);
}
return ar;
}, []);
Logger.log("VALUES "+values.length);
Logger.log("VALUES "+values);
//Logger.log("Found Items:" + items.length);
return [];
}