Create spreadsheet alongside file upload with Google App Script - google-apps-script

I'm having a surprisingly hard time finding basic examples of setting something like this up. I'm pouring through the documentation, but the basic functions simply will not work. Could really use some advice.
I have file upload working thanks to another tutorial, but I would like to create a spreadsheet as well (or simply OPEN the spreadsheet if it already exists) to store additional info such as the name of the uploader, a URL of the file, etc. No dice!
SERVER.GS:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var ss = SpreadsheetApp.create("TEST123");
var sheet = ss.getSheets()[0];
// Appends a new row with 2 columns to the bottom of the
// spreadsheet containing the values in the array
sheet.appendRow(["Jackson Jones", "jJones#email.com"]);
var dropbox = "Student Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
FORM.HTML:
<form id="myForm">
<input type="text" name="myName" placeholder="Your full name...">
<input type="file" name="myFile">
<input type="submit" value="Upload File"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form>
<div id="output"></div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
Of course eventually I would use form.myName and such to populate the spreadsheet, but I can't even get their example code to run.

It looks like you have some problems with your form syntax. Here is a version that will do what you are after -- it a modified version of the code tutorial present the Apps Script HTMLService documentation.
Note I am using IDs to identify the drop folder and log spreadsheet for convenience (note that more than one file/folder can have the same name in Drive, so use of IDs is generally preferable to finding files by name).
Code.gs:
var dropBoxId = "012345679abcdefg"; // Drive ID of 'dropbox' folder
var logSheetId = "abcdefghijklmnopqrstu123"; // Drive ID of log spreadsheet
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('InputForm.html');
}
function uploadFiles(formObject) {
try {
// Create a file in Drive from the one provided in the form
var folder = DriveApp.getFolderById(dropBoxId);
var blob = formObject.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + formObject.myName);
// Open the log and record the new file name, URL and name from form
var ss = SpreadsheetApp.openById(logSheetId);
var sheet = ss.getSheets()[0];
sheet.appendRow([file.getName(), file.getUrl(), formObject.myName]);
// Return the new file Drive URL so it can be put in the web app output
return file.getUrl();
} catch (error) {
return error.toString();
}
}
InputForm.html:
<form id="myForm">
<input type="text" name="myName" placeholder="Your full name..."/>
<input name="myFile" type="file" />
<input type="button" value="Submit"
onclick="google.script.run
.withSuccessHandler(updateUrl)
.withFailureHandler(onFailure)
.uploadFiles(this.parentNode)" />
</form>
<div id="output"></div>
<script>
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Got it!';
}
function onFailure(error) {
alert(error.message);
}
</script>
<style>
input { display:block; margin: 20px; }
</style>

5 Suggestion to Ryan Roth's Script:
1. "Timestamp" column is not created when somebody fills out form.
2. "required" field attribute not working.
3. The uploaded file should be submitted to google drive with folder created with uploader's name.
4. After submitting the form, the fields doesn't not refresh leaving the entered data as it is.
5. The standalone app is not embeddable in website.
If anyone have the updated script please do share below.

Related

Upload Image in google sheet cell using google apps script?

I am looking to upload an image into google sheet cell using a google apps script, I found a script that uploads image into Google Drive folder and then gets the image url into sheet that can be manipulated to get the image:
Here is the first function:
Code.gs
function addImage() {
var filename = 'Row';
var htmlTemp = HtmlService.createTemplateFromFile('Index');
htmlTemp.fName = filename;
htmlTemp.position = 2;
var html = htmlTemp.evaluate().setHeight(96).setWidth(415);
var ui = SpreadsheetApp.getUi();
ui.showModalDialog(html, 'Upload');
}
Following is the return function:
Code.gs
function upload(obj) {
//Retrieve the input data of the Form object.
var newFileName = obj.fname;
var rowNum = obj.position;
var blob = obj.file;
var upFile = DriveApp.getFolderById('[folderid]').createFile(blob).setName(newFileName);
var fileUrl = upFile.getUrl();
var urlCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(rowNum,5);
urlCell.setValue('=HYPERLINK("' + fileUrl + '","View image")');
}
This is the html part:
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
Please upload image below.<br /><br />
<input type="hidden" name="fname" id="fname" value="<?= fName ?>"/>
<input type="hidden" name="position" id="position" value="<?= position ?>"/>
<input type="file" name="file" id="file" accept="image/jpeg,.pdf" />
<input type="button" value="Submit" class="action" onclick="formData(this.parentNode)" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</form>
<script>
//Disable the default submit action using “func1”
window.onload=func1;
function func1() {
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
});
}
function formData(obj){
google.script.run.withSuccessHandler(closeIt).upload(obj);
}
function closeIt(e){
console.log(e);
google.script.host.close();
};
</script>
</body>
</html>
When I ran the addImage() function, a dialog box popped up in which I uploaded a jpeg image, but when I clicked on submit button, it did not do anything and stuck there, any help would be much appreciated. Thanks
Issue and workaround:
From [Fixed] Google Apps Script Web App HTML form file-input fields not in blob compatible format, in the current stage, when Web Apps is used, the file object in the form object can be parsed by google.script.run. But, unfortunately, it seems that when a dialog and sidebar are used, this cannot be parsed. So, in the current stage, as the current workaround, it is required to parse the file object on the Javascript side. When this is reflected in your script, how about the following modification?
Google Apps Script side: Code.gs
Please `upload as follows.
function upload(obj, rowNum) {
var newFileName = obj[2];
var blob = Utilities.newBlob(...obj);
var upFile = DriveApp.getFolderById('[folderid]').createFile(blob).setName(newFileName);
var fileUrl = upFile.getUrl();
var urlCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(rowNum, 5);
urlCell.setValue('=HYPERLINK("' + fileUrl + '","View image")');
return "Done.";
}
HTML & Javascript side: Index.html
Please formData as follows.
function formData(obj) {
const file = obj.file.files[0];
const fr = new FileReader();
fr.readAsArrayBuffer(file);
fr.onload = f =>
google.script.run.withSuccessHandler(closeIt).upload([[...new Int8Array(f.target.result)], file.type, obj.fname.value], obj.position.value);
}

Only the else condition works in my google apps script Twilio Fax sending web app

I'm having an issue with my If statement.
Basically I set up a fax app with Twilio and Google apps script.
I give the user a choice to upload a document or send out one that stored on my Google drive.
If I upload a file it works. But if I check the checkbox to send a pre-set document, which I'm trying to accomplish by using the If statement it doesn't send.
I troubleshooted, and found that the If statements is getting a TRUE and FALSE value.
I think the problem is that when there is no file passed into the function it doesn't work. The thing is I'm avoiding the file by the If statement so why is it not working.
Below is my HTML file and server side apps script.
Any suggestions?
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(blob, name, number, test) {
//get destination number
var num = number;
var prefix = "+1";
var removeDashes = num.replace(/-/g,"");
var fullNumber = prefix + removeDashes;
var output;
if (test){
output = "APPLICATION SENT!";
}else{
output = "FAX SENT!";
}
var url;
if (test) {
var appl = DriveApp.getFileById('xxxxxxxxx');
var appurl = appl.getDownloadUrl();
url = appurl;
} else {
var folder = DriveApp.getFolderById('xxxxxxxxxxx');
var blob = blob.split(",");
var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf');
var fileName = blob.setName(name).getName();
var file = folder.createFile(blob);
//allow access to Twilio
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
//get file url
var id = file.getId();
var getfile = DriveApp.getFileById(id);
var getnewurl = getfile.getDownloadUrl();
var url = getnewurl;
}
//send fax
var faxUrl = "https://fax.twilio.com/v1/Faxes";
var payload = {
"From" : "+1888888888",
"To": fullNumber,
"MediaUrl" : url,
"Method" : "POST",
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxx")
};
UrlFetchApp.fetch(faxUrl, options);
return "succes" + output;
}
Here is the HTML file: (I removed the <style> in order to shorten)
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function upload() {
var file = document.getElementsByName('myFile')[0].files[0];
var number = document.getElementsByName('Pnumber')[0].value;
var test = document.getElementsByName("entered")[0].checked;
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, test);
return false;
}
reader.readAsDataURL(file);
}
function fileUploaded(status) {
document.getElementById("myForm").reset();
document.getElementById('output').innerHTML = status;
}
</script>
</head>
<body>
<div align="center">
<h1 align="center" style="color:darkblue">FAX APP</h1>
<h2 align="center">SEND OUTGOING FAX</h2>
<hr>
<form id="myForm" align="center">
<label for="pdf">Choose a PDF file to upload -- <b>OR</b>-- Check "SEND APPLICATION" </label>
<br>
<input id="pdf" type="file" name="myFile" >
<br><br>
<input type="checkbox" style="width:25px ; height:25px" name="entered">
<label for="entered" style="font-size:30px" > SEND APPLICATION</label>
<br><br>
<label for="phonenumber">Enter Destination Number</label>
<br>
<input id="phonenumber" type="text" name="Pnumber" placeholder="Phone Number" >
<br>
<input type="submit" value="SEND FAX" onclick="upload()" >
</form>
<p><b>FAX DELIVERY STATUS:</b></p>
<div id="output"align="center"><b></b></div>
<br>
<a href="https://drive.google.com/drive/folders/xxxxxxxxxxxxxxxxxxx?usp=sharing"
target="_blank">SENT FAX DOCUMENTS</a>
</div>
</body>
</html>
BELOW IS THE NOW WORKING CODE OF GOOGLE SCRIPT SIDE AND HTML
THANKS TO #Tanaike's HELP
CURRENT GOOGLE SCRIPT SIDE CODE:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(blob, name, number, test) {
//get destination number
var num = number;
var prefix = "+1";
var removeDashes = num.replace(/-/g,"");
var fullNumber = prefix + removeDashes;
var output;
if (test){
output = "APPLICATION SENT!";
}else{
output = "FAX SENT!";
}
var url;
if (test) {
var appl = DriveApp.getFileById('xxxxxxxxxxxxxxxxxxxxxxx');
var appurl = appl.getDownloadUrl();
url = appurl;
} else {
var folder = DriveApp.getFolderById('xxxxxxxxxxxxxxxxxxxxxxxxxxx');
var blob = blob.split(",");
var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf', name);
var file = folder.createFile(blob);
//allow access to Twilio
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
//get file url
var id = file.getId();
var getfile = DriveApp.getFileById(id);
var getnewurl = getfile.getDownloadUrl();
url = getnewurl;
}
//send fax
var faxUrl = "https://fax.twilio.com/v1/Faxes";
var payload = {
"From" : "+188888888888",
"To": fullNumber,
"MediaUrl" : url,
"Method" : "POST",
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxxxxxxxxxx:xxxxxxxxxxxxxxxxxxx")
};
UrlFetchApp.fetch(faxUrl, options);
return "Success - " + output;
}
CURRENT HTML SIDE CODE:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function upload() {
var file = document.getElementsByName('myFile')[0].files[0];
var number = document.getElementsByName('Pnumber')[0].value;
var test = document.getElementsByName("entered")[0].checked;
if(!test){
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, null);
return false;
}
reader.readAsDataURL(file);
}else{
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(null, null, number, test);
return false;
}
}
function fileUploaded(status) {
document.getElementById("myForm").reset();
document.getElementById('output').innerHTML = status;
}
</script>
</head>
<body>
<div align="center">
<h1 align="center" style="color:darkblue">FAX APP</h1>
<h2 align="center">SEND OUTGOING FAX</h2>
<hr>
<form id="myForm" align="center">
<label for="pdf">Choose a PDF file to upload -- <b>OR</b>-- Check "SEND APPLICATION" </label>
<br>
<input id="pdf" type="file" name="myFile" >
<br><br>
<input type="checkbox" style="width:25px ; height:25px" name="entered">
<label for="entered" style="font-size:30px" > SEND APPLICATION</label>
<br><br>
<label for="phonenumber">Enter Destination Number</label>
<br>
<input id="phonenumber" type="text" name="Pnumber" placeholder="Phone Number" >
<br>
<input type="submit" value="SEND FAX" onclick="upload()" >
</form>
<p><b>FAX DELIVERY STATUS:</b></p>
<div id="output"align="center"><b></b></div>
<br>
<a href="https://drive.google.com/drive/folders/xxxxxxxxxxxxxxxx?usp=sharing"
target="_blank">SENT FAX DOCUMENTS</a>
</div>
</body>
</html>
I believe your goal as follows.
You want to remove the error when SEND APPLICATION is checked without selecting a file.
Modification points:
When the file is not selected, an error occurs at FileReader because file is undefined. I think that this might be the reason of your issue.
In this case, I would like to propose the function upload() at Javascript side as follows.
if (file && !test) {}else{} is used. By this,
When the file is selected AND SEND APPLICATION is not checked, the selected file is used.
When the file is not selected OR SEND APPLICATION is checked, the file of var appl = DriveApp.getFileById('xxxxxxxxx') is used.
About this, please modify the if statement for your actual situation.
Modified script:
When your script is modified, please modify upload() at Javascript side as follows.
function upload() {
var file = document.getElementsByName('myFile')[0].files[0];
var number = document.getElementsByName('Pnumber')[0].value;
var test = document.getElementsByName("entered")[0].checked;
// I modified below script.
if (file && !test) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, test);
return false;
}
reader.readAsDataURL(file);
} else {
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(null, null, number, test);
}
}
In this modification, Google Apps Script side is not modified.
Added:
I think that your current issue is due to that you changed Google Apps Script from the script in the initial question. In the current script, name is removed at Google Apps Script and Javascript. By this, an error occurs at createFile. Please use name as follows.
From:
var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf');
To:
var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf', "sample");
In this case, the filename is a temploral. So you can use various name like "sample", "temp" and so on.
And when you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.
And in your current script, if (!test) { is used. In this case, when the button is cliced without selecting file and cheking the checkbox, an error occrurs. Please be careful this.

How to get file(s) from an HTML file input and send it as an attachment to an email in Google Apps Script?

This HTML code takes file inputs using Google Script's class HTML service :
(SEE BELOW)
I would like to get the value(s)(the files) of the input field, send to the my .gs file and send that as an attachment to the email.
Getting the value from the input field simply returns the directory of the file, which is no help because Google Apps Script can't obtain files from local drive.
I have done a lengthy research with this problem and I can't find anyone with a similar issue.
Stack Code.gs
function myFunction() {
var html = HtmlService.createHtmlOutputFromFile('Stack HTML').setWidth(250).setHeight(250);
SpreadsheetApp.getUi().showModalDialog(html,'Get File');
}
function processEmail(files){
var subject = 'Subject';
var message = 'Test';
var recipient = 'test#gmail.com';
GmailApp.sendEmail(recipient, subject, message, {attachments: files, htmlBody: message, name:'Stack Overflow Test'}); // Doesn't work
}
Stack HTML.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div>
<input type="file" id= "file" multiple = "true">
</div>
</form>
<br><div style="text-align:center"> <input type="submit" name = "submitButton" onclick = "send()" id = "sendButton" value="Send"></div>
<script>
function done(e){
google.script.host.close();
}
function send(){
var files = document.getElementById("file").value;
console.log(files);
google.script.run.withSuccessHandler(done).processEmail(files);
}
</script>
</body>
</html>
You want to upload multiple files from local PC to Google Drive using HTML and Javascript.
You want to send the uploaded files as the attachment files of an email.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
Solution:
From your question, the files are used as the attachment files of an email. So I thought that the following flow can be used for your situation.
Retrieve all files from the local PC.
All files are summarized as an object.
At this time, the files are converted to the base64 string value.
Send the object to Google side.
Convert the object to file blob at GAS side.
Modified script:
Please modify send() in HTML side as follows.
function send() {
const f = document.getElementById('file');
Promise.all([...f.files].map((file, i) => {
const fr = new FileReader();
return new Promise(r => {
fr.onload = e => {
const data = e.target.result.split(",");
r({fileName: file.name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]});
}
fr.readAsDataURL(file);
});
}))
.then(obj => {
google.script.run.withSuccessHandler(done).processEmail(obj);
});
}
And please modify processEmail() in GAS side as follows.
function processEmail(obj){
var files = obj.map(function(e) {return Utilities.newBlob(Utilities.base64Decode(e.data), e.mimeType, e.fileName)});
var subject = 'Subject';
var message = 'Test';
var recipient = 'test#gmail.com';
GmailApp.sendEmail(recipient, subject, message, {attachments: files, htmlBody: message, name:'Stack Overflow Test'});
}
References:
FileReader
Class Utilities
Uploading Multiple Files From Local To Google Drive using Google Apps Script

Function called from webapp does not send email

I'm having a problem with Google Scripts.
I'm trying to do an open questionnaire that allows anonymous file uploads to a specific folder on my Google Drive, and afterwards sends me a notification email to my mail. It uploads the file fine, but the email is not sent.
In debugging mode, it sent the email.
Here is my code:
<form id="myForm">
<input type="text" name="myName" placeholder="Su Nombre..">
<input type="file" name="myFile">
<input type="submit" value="Subir Archivo"
onclick="this.value='subiendo..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form>
And the Google Script file:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var folder = DriveApp.getFolderById(/*folder id*/);
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Subido Por " + form.myName);
// email
var asunto = "Testing attaching file";
var correo = /*my email address*/;
var options = {attachment : [form.MyFile]};
MailApp.sendEmail(correo, asunto, emailBody, options);
return "Archivo Subido Con Exito " + file.getUrl();
}
catch (error) {
return error.toString();
}
}

Create a Google Sheet with Plain Text Cells to Prevent Auto-Format of Strings

I work with a group of users who frequently need to edit CSV files that contain Strings that look like dates and numbers. These strings need to be preserved as strings.
For example
2016-04
Is converted to a date field
4/1/2016
When editing a new spreadsheet, we must set the format of every cell to TEXT/Plain Text to prevent this conversion. When importing an existing CSV file, we need to prevent this conversion from taking place.
Unfortunately, Excel and Google Sheets auto-convert strings on import or file open.
What is the best way to prevent this conversion in Google Sheets?
Here is my current solution using Google Apps Script to create a web service that converts CSV content into a new Google Sheet.
Code.gs
//Display the interactive landing page for this servcie
function doGet() {
var html = HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
//Create a global object to store the response from a POST request
var RESP;
//Handle a POST request directly to this service.
//The parameter "data" should contain CSV content
//A response page will be generated with a link to the Google Sheet that is generated
function doPost(req) {
RESP = createPlainTextSpreadsheet(req.parameter.data);
var temp = HtmlService.createTemplateFromFile('Response');
return temp.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
//Handle CSV content sent from the interactive landing page for this script
//Return a string representation of a JSON object with the name and URL of the generated Google Sheet
function doTextPost(req) {
var resp = createPlainTextSpreadsheet(req.data);
return JSON.stringify(resp);
}
//Handle file upload content sent from the interactive landing page for this script
//Return a string representation of a JSON object with the name and URL of the generated Google Sheet
function processFile(form) {
var blob = form.file;
var resp = createPlainTextSpreadsheet(blob.getDataAsString());
return JSON.stringify(resp);
}
//Generate a new Google Sheet containing the CSV data that is provided
//The new Google Sheet will be named "import.YYYY-MM-DD_HH:MM.csv in Google Drive
//All data cells will be set as "Plain Text" to prevent auto-conversion of strings that look like dates and numbers
//Text wrap will be enabled for all data cells
//The header row will be highlighted and the columns will be auto-sized
//Return a JSON object containing the name and URL of the new Google Sheet
function createPlainTextSpreadsheet(data) {
var arr = Utilities.parseCsv(data);
if (arr.length == 0) return "No data";
var formattedDate = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd_HH:mm");
var spreadsheet = SpreadsheetApp.create("import."+formattedDate+".csv");
var sheet = spreadsheet.getActiveSheet();
var range = sheet.getRange(1, 1, arr.length, arr[0].length);
var rangeR1 = sheet.getRange(1, 1, 1, arr[0].length);
range.setValue("");
range.setNumberFormat("#STRING#");
range.setValues(arr);
range.setWrap(true);
rangeR1.setBackground("yellow");
rangeR1.setFontWeight("bold");
for(var i=1; i<=arr[0].length; i++) {
sheet.autoResizeColumn(i);
if (sheet.getColumnWidth(i) > 300) {
sheet.setColumnWidth(i, 300);
}
}
return {name: spreadsheet.getName(), url: spreadsheet.getUrl()};
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//Pass the uploaded file object (formObject.file) to the web service, extract CSV content from the uploaded file
function handleFormSubmit(formObject) {
jQuery("input:button").attr("disabled",true);
google.script.run.withSuccessHandler(updateOutput).withFailureHandler(fail).processFile(formObject);
}
//Pass CSV content as a string (formObject.data)
function handleFormPost(formObject) {
jQuery("input:button").attr("disabled",true);
google.script.run.withSuccessHandler(updateOutput).withFailureHandler(fail).doTextPost(formObject);
}
//Display the name and URL of the Google Sheet that was created
function updateOutput(data) {
var resp = jQuery.parseJSON(data);
document.getElementById("output").innerHTML="<a href='"+resp.url+"'>"+resp.name+"</a> created on Google Drive";
}
//Display and error dialog
function fail(data) {
alert("FAIL: "+data);
}
</script>
</head>
<body>
<h1>Create a Plain Text Google Spreadsheet That Prevents Auto-Format of Data Cells</h1>
<div>In addition to the forms provided below, you can POST data to this webservice directly.</div>
<h2>Upload a CSV File</h2>
<form id="myForm">
<div>
<label for="file">CSV File to Upload</label>
<input name="file" type="file"/>
</div>
<div>
<input type="button" value="Upload CSV" name="button" onclick="handleFormSubmit(document.getElementById('myForm'))"/>
</div>
</form>
<hr/>
<h2>Upload the Text from a CSV file</h2>
<form id="myPostForm" method="POST">
<div>
<label for="data">CSV File to Upload</label>
<br/>
<textarea name="data" rows="10" cols="100"></textarea>
</div>
<div>
<input type="button" value="Upload Data" name="button" onclick="handleFormPost(document.getElementById('myPostForm'))"/>
</div>
</form>
<hr/>
<h2>Link to new Spreadsheet</h2>
<div id="output">Upload CSV text in order to generate a new Google Sheet</div>
</body>
</html>
Response.html
<!DOCTYPE html>
<html>
<body>
Google Sheet <?= RESP.name ?> Created
</body>
</html>