Convert "," to ";" in a CSV file Google script - export-to-csv

With the below code my goal is to extract a sheet from the Google sheet file in CSV format. However, when I want to convert the , to ; the following error message appears:
r.join is not a function
Could you please help me to solve this problem.
Also, do you think it is possible to download this new file directly to the desktop of the computer ?
function sheetToCsv(){
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "Int_Module";
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 newfile = [result].map(r => r.join(";")).join("\n");
newfile.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
}

I understand that there is 2 questions ... how to produce CSV file with semi-colon, and how to download the file directly to your PC.
1- To produce the csv content, try
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
2- To download, you will have to go through an html page.
Try this for both needs
function downloadMyCSVFile() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
var html = HtmlService.createHtmlOutput(`
<html><body onload="document.getElementById('dwn-btn').click()">
<textarea id="text-val" rows="10" style="display:none;">${content}</textarea>
<input type="button" id="dwn-btn" value="Download text file" style="display:none;"/>
<script>
window.close = function(){window.setTimeout(function(){google.script.host.close()},100)}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function(){
var text = document.getElementById("text-val").value;
var filename = "${sh.getName()}.csv";
download(filename, text);
close();
}, false);
</script>
</body></html>
`)
.setWidth(250).setHeight(100);
SpreadsheetApp.getUi().showModalDialog(html, "Downloading ...");
}

Related

Google Sheets Script MailApp.sendEmail prompt

Trying to alter the following script to prompt for an email address. I was able to load this as an add-on in Google sheets and it works fine but I want to be able to change the "To" address each time I run it. Is there any way to force some sort of prompt so that I can input the email address on each run?
function onOpen() {
// Try New Google Sheets method
try{
var ui = SpreadsheetApp.getUi();
ui.createMenu('SendMail')
.addItem('Send Report', 'getGoogleSpreadsheetAsExcel')
.addToUi();
}
// Log the error
catch (e){Logger.log(e)}
}
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=csv";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".csv");
MailApp.sendEmail("xxxxxx#gmail.com", "Stock report of today", "The XLSX file is attached", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
All you need to do is get the UI of the spreadsheet and send a prompt then run it through an if statement to make sure the correct button is pressed, try the below:
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=csv";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".csv");
var ui = SpreadsheetApp.getUi();
var prompt = ui.prompt('Enter email address:', '',ui.ButtonSet.OK_CANCEL);
if (prompt.getSelectedButton() == 'OK') {
var mail = prompt.getResponseText();
MailApp.sendEmail(mail, "Stock report of today", "The XLSX file is attached", {attachments: [blob]});
}
} catch (f) {
Logger.log(f.toString());
}
}
The code prompts for an email address:
var prompt = ui.prompt('Enter email address:', '',ui.ButtonSet.OK_CANCEL);
Then runs through a quick if statement to make sure the button pressed is 'OK', if it's cancelled it'll do nothing.
if (prompt.getSelectedButton() == 'OK') {
var mail = prompt.getResponseText();
MailApp.sendEmail(mail, "Stock report of today", "The XLSX file is attached", {attachments: [blob]});
}
As you can see, var mail is used in the sendEmail(), meaning it'll use whatever you entered as your email address as the recipient of your email.

Auto Login to User from Site to Disqus

I added the Disqus to my website and making use of the script
SSO configuration is like this:
Name: example
Slug: example
no call back url is set at my end.
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'myexample';
var disqus_identifier = 'http://www.example.com/Welcome...
var disqus_title = 'My Example';
var disqus_url = 'http://www.example.com/Welcome...
var remote_auth_s3 = "<%=Payload%>";//Its generate by server side code
var api_key = "Public Api Key Is here";
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
I am just using the above script and passing the values.
Will this script auto login my website users to Disqus or I have to do other extra efforts.
Thanks Dalvir
My issue fixed after making use of variable like this
var disqus_config = function () {
// The generated payload which authenticates users with Disqus
this.page.remote_auth_s3 = "<%=Payload%>";
this.page.api_key = "<%=Key%>";
};

A open source RTMP streaming server for stream mp3 on deman?

I need a open source RTMP server for stream mp3s on demand for linux(centos), i found a few but these dont let me stream on demand, just only live. thanks
this does on demand ... just install node.js and execute using :
node file_containing_below.js
and yes consider it open source ;-)
var http = require('http');
var fs = require('fs');
var util = require('util');
var port = 8888;
var host = "localhost";
http.createServer(function (req, res) {
var path = "/path/to/some/video/or/audio/file.mp3"; // mp4 or most any video/audio file
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers.range) { // meaning client (browser) has moved the forward/back slider
// which has sent this request back to this server logic ... cool
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1;
var chunksize = (end-start)+1;
console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
file.pipe(res);
} else {
console.log('ALL: ' + total);
res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'video/mp4' });
fs.createReadStream(path).pipe(res);
}
}).listen(port, host);
console.log("Server running at http://" + host + ":" + port + "/");
now just point some client (your browser) at URL
http://localhost:8888/
and yes once playing the forward/back sliders automagically work on an arbitrary client (browser)

How to return an image from GridFS in a JSON object (or similarly convenient format)?

I have a form that allows a user to upload an image to GridFS asynchronously.
I'd like to be able to get the image back from the sever so that I can add it to a div via jQuery.
Previously, in other areas of the app, I've been using getJSON() requests that return content from the server in JSON format with:
Bottle
response.content_type = 'application/json'
return dumps(results)
And then accessing individual fields in jQuery with:
HTML
$("#my_content").append(results.my_db_key)
Is it possible to return an image back in a similarly convenient format that is easy to reference and manipulate in jQuery?
As stated, I'd like to be able to update a div with the retrieved image.
Working Code Below - Just need help with the Bottle part
Form
<form id="ajaxUploadForm" enctype="multipart/form-data" method="post" action="/upload">
<input type="file" id="my_img_upload_input" name="my_image">
<input type="submit" value="upload">
</form>
jQuery
$(document).on("click","#ajaxUploadForm input[type=submit]", function (e) {
e.preventDefault();
var myShinyData = new FormData($("#ajaxUploadForm")[0]);
$.ajax({
url: '/upload',
data: myShinyData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert("This is a success message");
}
});
});
Bottle Route
#route('/upload', method='POST')
def do_upload():
uploaded_image = request.files.my_image
name, ext = os.path.splitext(uploaded_image.filename)
if ext not in ('.png','.jpg','.jpeg'):
return "File extension not allowed."
if uploaded_image and uploaded_image.file:
raw = uploaded_image.file.read()
filename = uploaded_image.filename
dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
fs.put(raw,filename=filename)
thing = fs.get_last_version(filename=filename)
# somehow return the image in a convenient format
# that can be referenced in jQuery.
# response.content_type = 'image/jpeg' OR
# response.content_type = 'application/json' OR
# something else?
# return thing
return "You missed a field."
Edit:
Here is one solution - using the base64 encoding approach:
dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
filename = "my_image.jpg"
my_image_file = fs.get_last_version(filename=filename)
encoded_img_file = base64.b64encode(my_image_file.read())
return encoded_img_file
Accessed on the front end with:
$("#my_img").attr("src", "data:image/png;base64," + data);
from https://stackoverflow.com/a/21213523/1063287

Getting Image path instead of Image - PhoneGap Listview

I am working on an PhoneGap application in which I am saving user's name , number and Email , after that I am displaying that data to another page in list - view. That has been done very successfully. But now when I want to store Image of user in my local Storage, I am getting the path of image instead of Image.
I am saving my data in this way :
<SCRIPT Language="JavaScript" charset="utf-8" type="text/javascript">
var userName, userNumber, userEmail, userImage ;
function showAndClearField(frm)
{
userName = frm.name.value;
userNumber = frm.number.value;
userEmail = frm.email.value;
if (frm.name.value == "" )
{
alert("Please enter your name!")
}
else if(frm.number.value == "")
{
alert("Please enter your number!")
}
else if(frm.email.value == "")
{
alert("Please enter your Email !")
}
else
{
alert("Name : " + userName + '\n' + " Number: " + userNumber + '\n' + " Email: " + userEmail )
frm.name.value = ""
frm.number.value = ""
frm.email.value = ""
var db = window.openDatabase("TestingDemo", "1.0", "PhoneGapTesting Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx)
{
tx.executeSql('INSERT INTO DEMO (id, data, userName, userNumber, userEmail, userImage) VALUES (1, "Third row", "'+ userName +'" , "'+ userNumber +'" , "'+ userEmail +'", "'+ userImage +'")');
}
While displaying data I am using following code :
var nameOfUser , numberOfUser , emailOfUser, imageOfUser;
for (var i=0; i<len; i++)
{
nameOfUser = results.rows.item(i).userName;
numberOfUser = results.rows.item(i).userNumber;
emailOfUser = results.rows.item(i).userEmail;
imageOfUser = results.rows.item(i).userImage;
numArr.push({ name : nameOfUser , number : numberOfUser , email : emailOfUser, image : imageOfUser });
}
function createCheckboxes(){
$("#createBtn").remove();
$("#content").append('<fieldset id="cbFieldSet" data-role="controlgroup" style = "padding : 20px" >');
var length = numArr.length;
for(var i=0;i<length;i++)
{
$("#cbFieldSet").append('<input type="checkbox" name= "cb-'+i+'" id="cb-' + i +'" number = "'+numArr[i].name+'"/> <label for= "cb-'+i+'">' + "Name : " + numArr[i].name + ' <br>' + "Email : " + numArr[i].email +' <br>' + " Number " + numArr[i].number +' <br>' + numArr[i].image + ' <br><br> </label>' );
alert("List Created !");
}
alert("Out of For loop !");
$("#content").trigger("create");
alert("Content Created !");
$("#showBtn").css("visibility","visible");
}
function showSelectedNames(){
var count = $("#cbFieldSet input:checked").length;
var str = '';
for(i=0;i<count;i++){
str += ' '+$("#cbFieldSet input:checked")[i].value;
}
alert("You selected----"+str);
}
</script>
How the view I am getting is :
i do not know about this particular program,
but i do know that you are passing the image location as an argument, (text).
the other arguments are also text, and you have no done anything differently with the image argument to have the UI display an image. maybe you are missing image tags, or an "getImage(location)" type function.
edit:
<img src="PATH" />
you need to put PATH as image location and this is what will display it.