google app script export csv with semicolon instead of comma - google-apps-script

I am using the code below to export a google spreadsheet to CSV in a specific folder.
I need to have a semicolon (;) as delimiter instead of a comma (,)
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssname = ss.getName();
var sheet = ss.getActiveSheet();
var parentFolder = DriveApp.getFolderById("MyID");
var folder = parentFolder;
var curDate = Utilities.formatDate(new Date(), "GMT+1", "yyyyMMdd")
var fileName = "MyName" + curDate + ".csv";
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?
exportFormat=csv&format=csv";
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
folder.createFile(response.getBlob().setName(fileName));
}
Thank you for your help

You want to replace , to ; for the retrieved CSV data.
You want to create the replaced data as a file.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
The data that ; is used as the delimiter instead of , is no mimeType of text/csv. In this case, it is required to be text/plain.
In your script, I would like to propose the following 2 patterns.
Pattern 1:
In this pattern, the values are retrieved and the data separated by ; is created.
Modified script:
When your script is modified please modify as follows.
From:
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?
exportFormat=csv&format=csv";
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
folder.createFile(response.getBlob().setName(fileName));
To:
var values = sheet.getDataRange().getValues();
var outputData = values.map(r => r.join(";")).join("\n");
folder.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
Pattern 2:
In this pattern, the retrieved CSV data is converted.
Modified script:
When your script is modified please modify as follows.
From:
folder.createFile(response.getBlob().setName(fileName));
To:
var csvData = Utilities.parseCsv(response.getBlob().getDataAsString());
var outputData = csvData.map(r => r.join(";")).join("\n");
folder.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
Note:
Please enable V8.
Reference:
createFile(name, content, mimeType)
If I misunderstood your question and this was not the direction you want, I apologize.

Related

Convert Google Sheet to CSV then attach it to an email

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 })
}

Get specific Range to Export

can anyone help me with my problem?
Need to export a specific range (A1:J39), not the full sheet.
function SavePDFtoDrive() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ltrsht = ss.getSheetByName("Schichtübergabe-Protokoll");
var datasheet = ss.getSheetByName("Daten");
var sheets=SpreadsheetApp.getActiveSpreadsheet().getSheets();
for(var i =0;i<sheets.length;i++){
if(sheets[i].getName()!="Schichtübergabe-Protokoll"){ sheets[i].hideSheet() }
}
var pdf = DriveApp.getFileById(ss.getId());
var theBlob = pdf.getBlob().getAs('application/pdf').setName(datasheet.getRange("I8").getValue()+".pdf");
var folderID = "1dyKFNvQWrSiNFA8N5PyUMPJQpWSVhsLf"; // Folder id to save in a folder
var folder = DriveApp.getFolderById(folderID);
var newFile = folder.createFile(theBlob);
}
Answer:
Rather than getting your blob using DriveApp, you can obtain your blob from an export URL using UrlFetchApp.
More Information:
When you use DriveApp to create a blob of a file, it doesn't have the functionality to read the specifics of the file. In this case, you can't specify the range of a Sheet you wish to export with DriveApp.
You can, however, build a URL with all your export parameters and create your export in Drive by creating a blob of the response and creating it in Drive.
Code:
function SavePDFtoDrive() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ltrsht = ss.getSheetByName("Schichtübergabe-Protokoll");
var datasheet = ss.getSheetByName("Daten");
// build your URL:
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?"
//define your parameters:
var params = 'exportFormat=pdf&format=pdf'
+ '&portrait=false'
+ '&fitw=true'
+ '&gid=' + ltrsht.getSheetId()
+ '&range=A1:J39';
//get token for UrlFetch:
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + params, {
'headers': {
'Authorization': 'Bearer ' + token
}
});
var fileName = datasheet.getRange("I8").getValue() + ".pdf";
var theBlob = response.getBlob().setName(fileName);
var folderID = "1Hp-P1dzWaKHhhS2FTPzKib6pwJibS12t";
var folder = DriveApp.getFolderById(folderID);
folder.createFile(theBlob);
}
References:
Class UrlFetchApp | Apps Script | Google Developers
Related Questions/Answers:
how to print a long Google sheets column in fewer columns

google app script : how to change folder destination

I am using the script below to export a google spreadsheet to CSV (thank you ziganotschka).
I am trying to save the CSV in another folder than the same as my Spreadsheet.
I have a folder containing my spreadsheet and inside a subfolder ("Final_Export) where I would like the CSV to save in.
The app script I use is :
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssname = ss.getName();
var sheet = ss.getActiveSheet();
var folder = DriveApp.getFileById(ss.getId()).getParents().next();
var fileName = ssname + ".csv";
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?
exportFormat=csv&format=csv";
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
folder.createFile(response.getBlob().setName(fileName));
}
Thank you for your help
Finally, I found the solution.
I had this code :
var parentFolder = DriveApp.getFolderById("myFolderDestinationId");
var folder = parentFolder;

Google sheet create pdf from another sheet ID

Hi how could this code be modified to create a PDF file from another worksheet instead of the active open worksheet.
Here's part of the code I'm using and it works but I would like to create a PDF from another worksheet ID
Thanks
var source = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheet = spreadsheetId ? SpreadsheetApp.openById(spreadsheetId) : SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
var ticketnum = source.getSheetByName("Print Page").getRange('X1').getValue();
var body = 'Attached is your copy'
var Client = source.getSheetByName("Print Page").getRange('O5').getValue();
var Cons = source.getSheetByName("Print Page").getRange('T4').getValue() ;
var jobN = source.getSheetByName("Ticket PDF").getRange('G9').getValue() ;
var mailTo = source.getSheetByName("Print Page").getRange('Z1').getValue() ;
var folder = DriveApp.getFoldersByName('Ticket').next();
var token = ScriptApp.getOAuthToken();
var ssID = spreadsheetId;
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export"+
"?format=pdf&"+
'&portrait=true' +
'&fzr=true' +
'&fitw=True' +
//'&scale=4' +
'&top_margin=0.25' +
'&bottom_margin=0.25' +
'&left_margin=0.25' +
'&right_margin=0.25' +
'&horizontal_alignment=CENTER' +
'&gridlines=false'+
'&sheetnames=False';
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var pdf = response.getBlob().setName( Client + " " + ticketnum + " # " + jobN + " " + '.PDF');
folder.createFile(pdf)
How about this modification?
In this modification, it supposes that another worksheet ID in your question is the other sheet in the active Spreadsheet.
Modified script:
In order to export the specific sheet in the Spreadsheet as PDF file, you can use the query parameter of gid as follows.
From:
"?format=pdf&"+
To:
"?format=pdf&gid=" + spreadsheet.getSheetByName("###").getSheetId() + "&" +
In this case, please set the sheet name you want to export as a PDF to ###.
Note:
If you want to export several sheets in the Spreadsheet as a PDF file, this thread might be useful.
If I misunderstood your question and this was not the direction you want, I apologize.
Added
You want to export the specific Spreadsheet, which is not the active Spreadsheet, as a PDF file.
In your script, please give spreadsheetId. When spreadsheetId is not given the active Spreadsheet by var spreadsheet = spreadsheetId ? SpreadsheetApp.openById(spreadsheetId) : SpreadsheetApp.getActiveSpreadsheet();. And spreadsheetId is retrieved from the active Spreadsheet. So please modify as follows.
From:
var source = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheet = spreadsheetId ? SpreadsheetApp.openById(spreadsheetId) : SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
To:
var spreadsheetId = "###"; // Please set the Spreadsheet ID.
var source = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
var spreadsheetId = spreadsheet.getId();
If you want to export the specific sheet in the Spreadsheet, please use the query parameter gid. And if you want to export several sheets in the Spreadsheet, this thread might be useful.

how Send specific part of the sheet as email?

this script sends a pdf copy to my email when I type Send in cell L6 , this code send the whole sheet and I need to send as only A1:J22 , any Ideas ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
You want to retrieve the cells of A1:J22 and want to create them to PDF data.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In this modification, create a temporal sheet and copy the values of the cells of A1:J22 to it. Then, the temporal sheet is converted to PDF file. And, the temporal sheet is deleted.
Modified script:
When your script is modified, please modify as follows.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet(); // Added
// var sheetgId = ss.getActiveSheet().getSheetId(); // removed
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J22").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
}
}
References:
insertSheet(sheetName)
copyTo(destination)
deleteSheet(sheet)
If I misunderstood your question and this was not the direction you want, I apologize.