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?
Related
I have a simple Apps Script need, but can't find a near enough sample from the community.
I need to convert 2 sheets from a Google Spreadsheet, individually, as CSV files then attach them in an email.
So far, I found a script to convert a sheet into a CSV format and file it in a folder.
I looked for a script to add that will instead attach the CSV file to an email, but can't find anything which I can use based on my novice level of Apps Script knowledge.
Any help will be greatly appreciated. Thank you very much.
Script:
function sheet1ToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "xxxx"
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var folderId = "yyyy";
var csvContent = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv",
parents: [{id: folderId}]
}
var fileJson = Drive.Files.insert(csvContent,result)
}
In your showing script, an email is not sent. And, only one CSV file is created to Google Drive. From I need to convert 2 sheets from a Google Spreadsheet, individually, as CSV files then attach them in an email. and your showing script, when your showing script is modified, how about the following modification?
Modified script:
function myFunction() {
var emailAddress = "###"; // Please set your email address.
var sheetNames = ["Sheet1", "Sheet2"]; // Please set your 2 sheet names you want to use.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssID = ss.getId();
var requestData = { "method": "GET", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
var blobs = sheetNames.map(s => {
var params = ssID + "/export?gid=" + ss.getSheetByName(s).getSheetId() + "&format=csv";
var url = "https://docs.google.com/spreadsheets/d/" + params;
return UrlFetchApp.fetch(url, requestData).getBlob().setName(s); // <--- Modified
});
MailApp.sendEmail({ to: emailAddress, subject: "sample subject", body: "sample body", attachments: blobs });
}
When this script is run, an email is sent by including 2 CSV files as the attachment files.
References:
map()
sendEmail(message)
function myfunk() {
const folder = DriveApp.getFolderById("folderid");
const ss = SpreadsheetApp.getActive();
const names = ["Sheet1", "Sheet2"];
const params = { "method": "GET", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
let bA = [];
names.forEach(n => {
let sh = ss.getSheetByName(n);
let url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?gid=" + sh.getSheetId() + "&format=csv";
let r = UrlFetchApp.fetch(url, params);
let csv = r.getContentText();
let file = folder.createFile(n, csv, MimeType.CSV);
bA.push(file.getBlob());
})
GmailApp.sendEmail(recipient, subject, body, { attachments: bA })
}
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
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]);
I'm trying to use a script given in answer to this question
google spreadsheet script - Enable filter with a range by script
The aim is to create a basic filter on a spreadsheet.
This is the script
function applyFilter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssId = ss.getId();
var dataSheet = ss.getActiveSheet();
var lastRow = dataSheet.getLastRow();
var lastColumn = dataSheet.getLastColumn();
var sheetId = dataSheet.getSheetId();
var filterSettings = {
"range": {
"sheetId": sheetId,
"startRowIndex": 0,
"endRowIndex": lastRow,
"startColumnIndex": 0,
"endColumnIndex": lastColumn
}
};
var requests = [{
"setBasicFilter": {
"filter": filterSettings
}
}];
Logger.log(requests );
Logger.log(" ssid: " + ssId);
try{
Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId);
}
catch(e){Logger.log(e.message)}
}
These are the logs for my last attempt at running it the final line is the the error I'm getting
[17-09-17 10:32:57:700 BST] [{setBasicFilter={filter={range={endColumnIndex=26, endRowIndex=3756, sheetId=519417536, startColumnIndex=0.0, startRowIndex=0.0}}}}]
[17-09-17 10:32:57:701 BST] ssid: 1-05tNvAddY6gwzK9GYC4aMG347XARy_yUXZRcXxgHIk
[17-09-17 10:32:57:702 BST] Cannot call method "batchUpdate" of undefined.
The ssid is correct, the sheetId is correct. I have switched on the Google Sheets API in resources - I have enabled it in the Google API console
I'd be grateful if someone could tell me what I'm doing wrong
From your question, it is found that you have already enabled Sheets API at API console. But the error says Cannot call method "batchUpdate" of undefined.. So I think that Sheets API may have not been enabled at Advanced Google services. Please confirm it as follows.
In the script editor, select Resources > Advanced Google services
In the dialog that appears, click the on/off switch for Google Sheets API v4. Please turn on.
Click OK button.
If this was not useful for you, I'm sorry.
Edit :
In this sample, Sheets API v4 is used by UrlFetchApp.fetch() instead of Advanced Google services.
function applyFilter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssId = ss.getId();
var dataSheet = ss.getActiveSheet();
var lastRow = dataSheet.getLastRow();
var lastColumn = dataSheet.getLastColumn();
var sheetId = dataSheet.getSheetId();
var filterSettings = {
"range": {
"sheetId": sheetId,
"startRowIndex": 0,
"endRowIndex": lastRow,
"startColumnIndex": 0,
"endColumnIndex": lastColumn
}
};
var requests = [{
"setBasicFilter": {
"filter": filterSettings
}
}];
Logger.log(requests );
Logger.log(" ssid: " + ssId);
var url = "https://sheets.googleapis.com/v4/spreadsheets/" + ssId + ":batchUpdate"
var params = {
method:"post",
contentType: "application/json",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
payload: JSON.stringify({"requests": requests}),
muteHttpExceptions: true,
};
var res = UrlFetchApp.fetch(url, params).getContentText();
Logger.log(res)
}
I am fairly new to Google App Scripts. I need to build report inside Spreadsheet using Google-app-script functionality. I know how to download from DCM/DFM reporting excisting report to spreadsheet.
But I've failed to create new inside spreadsheet without downloading existing report from DCM/DFM. Is it possible? May be somebody has a sample (I hadn't found)? Or I've missed the concept and the only way to pull data into Spreadsheet is to create the report in DCM/DCF Report Builder first?
Here is the code i'm using.
function generateReport() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Reports');
var profileId = 2623334
var httpOptions = {
'headers': {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()}
}
var resource = {
'kind': 'dfareporting#report',
'accountId': '34405',
'type': 'STANDARD',
'name': 'Simple Report',
'criteria': {
'dateRange': {
'kind': 'dfareporting#dateRange',
'startDate': '2016-09-01',
'endDate': '2017-01-22',
},
'dimensions': [
{
'kind': 'dfareporting#sortedDimension',
'name': 'dfa:date',
}
],
'metricNames': [
'dfa:clicks', 'dfa:impressions'
],
}
}
var url = DoubleClickCampaigns.Reports.insert(resource, profileId);
var report = UrlFetchApp.fetch(url.urls.apiUrl, httpOptions);
for (var i=0; i<report.length; i++) {
var row = report[i];
sheet.getRange('A' + String(i+2)).setValue(row[0]);
sheet.getRange('B' + String(i+2)).setValue(row[1]);
sheet.getRange('C' + String(i+2)).setValue(row[2]);
}
}
The error appears here:
var report = UrlFetchApp.fetch(url.urls.apiUrl, httpOptions);
Error Messsage:
Can not read property "apiUrl" of undefined object.
My final script is:
function generateReport() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Reports');
var startDate = Browser.inputBox("Enter a start date (format: 'yyyy-mm-dd')");
var endDate = Browser.inputBox("Enter an end date (format: 'yyyy-mm-dd')");
var ReportName = Browser.inputBox("Enter your future report name");
var profileId = 2623334;
var resource = {
'kind': 'dfareporting#report',
'accountId': '34405',
'type': 'STANDARD',
'name': ReportName,
'criteria': {
'dateRange': {
'kind': 'dfareporting#dateRange',
'startDate': startDate,
'endDate': endDate,
},
'dimensions': [
{
'kind': 'fareporting#sortedDimension',
'name': 'dfa:date'
}
],
'metricNames': [
'dfa:clicks', 'dfa:impressions'
],
},
};
var httpOptions = {
'headers': {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()}
}
var url = DoubleClickCampaigns.Reports.insert(resource, profileId); //create Report inside DCM
var newReportId = Number(url.id); //get id of new Report
var additionalParameters = {
'synchronous': 'true'
};
var newReportRun = DoubleClickCampaigns.Reports.run(profileId, newReportId, additionalParameters); // run new Report in DCM
var newReportFileId = Number(newReportRun.id); //get id of New File
var newReportFile = DoubleClickCampaigns.Files.get(newReportId, newReportFileId);
if(newReportFile.urls) {
var httpOptions = {
'headers': {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()}
}
var contents = UrlFetchApp.fetch(newReportFile.urls.apiUrl, httpOptions); //Makes a request to fetch (получать) a URL using optional advanced parameters
if(newReportFile.format == 'CSV') {
var rows = Utilities.parseCsv(contents.getContentText());
if(rows && rows.length) {
var fileName = "DCM_test_work5";
var spreadSheet = SpreadsheetApp.create(fileName);
var sheet = spreadSheet.getActiveSheet();
rows.map(function(r) { sheet.appendRow(r); });
}
} else {
// Store the Excel file directly
Logger.log('not CSV!');
DocsList.createFile(contents.getBlob()).rename(newReportFile.fileName)
}
}
}