Google App Script - Export Active Sheet Without Sheet Name - javascript

I am using the script below to export a sheet as Excel file but the output file name is always Document Name + Sheet Name ("Exported - Report.xlsx"). How can I modify this to only use the sheet name as file name of the exported file ("Report.xlsx")?
function ExportSheet()
{
var SheetApp = SpreadsheetApp.getActive();
SheetApp.rename("Exported");
ShtURL = SheetApp.getUrl();
ShtID = SheetApp.getId();
ShtGID = SheetApp.getSheetId();
var url = ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID);
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
SheetApp.rename("Template");
}

In your situation, unfortunately, using the URL of ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID), the filename cannot be directly changed. So, in this case, how about the following modification?
Modified script:
function ExportSheet() {
var SheetApp = SpreadsheetApp.getActive();
SheetApp.rename("Exported");
ShtURL = SheetApp.getUrl();
ShtID = SheetApp.getId();
ShtGID = SheetApp.getSheetId();
var url = ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID);
// --- I modified below script.
var blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
var file = DriveApp.createFile(blob.setName(SheetApp.getSheets()[0].getSheetName()));
url = "https://drive.google.com/uc?export=download&id=" + file.getId();
// ---
var html = HtmlService.createHtmlOutput('<html><script>'
+ 'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+ 'var a = document.createElement("a"); a.href="' + url + '"; a.target="_blank";'
+ 'if(document.createEvent){'
+ ' var event=document.createEvent("MouseEvents");'
+ ' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+ ' event.initEvent("click",true,true); a.dispatchEvent(event);'
+ '}else{ a.click() }'
+ 'close();'
+ '</script>'
// Offer URL as clickable link in case above code fails.
+ '<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+ '<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+ '</html>')
.setWidth(90).setHeight(1);
SpreadsheetApp.getUi().showModalDialog(html, "Opening ...");
SheetApp.rename("Template");
file.setTrashed(true); // Added
}
In this modification, the converted XLSX is created as a temporal file. Here, the filename is changed. And, the file is downloaded using the URL of the created file. The temporal file is removed.
Note:
From your script, I thought that you might have wanted to use the sheet name of the 1st tab. But, if you want to give the specific filename, please modify SheetApp.getSheets()[0].getSheetName() of blob.setName(SheetApp.getSheets()[0].getSheetName()).

Related

How to download the file stored in azure blob to local machine using javascript?

I am uploading all the files in Azure blob storage. I am working on Dynamics 365 and want to download the file stored in Azure blob when I click the button in my Dynamics environment.
function getSelectedItems(selectedItems) {
for (i = 0; i < selectedItems.length; i++)
{
var selectedItem = selectedItems[i];
// Here you can use the information below to open a new window or whatever!
alert("Id=" + selectedItem.Id + "\nName=" + selectedItem.Name + "\nTypeCode=" + selectedItem.TypeCode.toString() + "\nTypeName=" + selectedItem.TypeName);
var new_fileName = selectedItem.Id;
var new_fileurl = '';
getUrlOfAttachmentFileFromBlob(new_fileurl,new_fileName);
}
}
function getUrlOfAttachmentFileFromBlob(new_fileurl,new_fileName) {
var fileHyperlink = '';
var blobUri = 'https://' + 'Storage_Account_Name' + '.blob.core.windows.net';
var containerName = 'trial';
var sas_token = 'sastoken' ;
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sas_token);
//.withFilter(new AzureStorage.Blob.ExponentialRetryPolicyFilter());
var downloadLink = blobService.getUrl(new_fileName, new_fileurl.replace('/'+containerName+'/',''), sas_token);
if (downloadLink != null)
{
alert("Link " + downloadLink);
downloadURI(downloadLink, new_fileName);
}
}
function downloadURI(uri, name)
{
var link = document.createElement("a");
link.setAttribute('download', name);
link.href = uri;
document.body.appendChild(link);
link.click();
}
I tried this code, but it's not working.
To add more details, I am calling the getSelectedItems function when I click the button inside the Dynamics environment. In this function, I am also getting the unique ID of the selected row in the grid. The unique ID is the name of the file in Azure blob storage.
Can you please provide me some reference on how can I download the files to the local machine using JavaScript?

Google Script - Export a document to PDF

I'm pretty new to programming and don't really know Javascript. Recently, to help out my mother with her business, I've came up with the script below.
Basically it takes information from a sheet (the sheet is filled with answers from Google Forms), copy a template document and then replace some fields in the copied document with those informations.
Now what I'm trying to do is to export the filled document to PDF, can someone help?
Here's the actual script:
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var timestamp = e.values[0];
//client info
var nome = e.values[1];
var cpf = e.values[2];
var rg = e.values[3];
var rua = e.values[4];
var numero = e.values[5];
var bairro = e.values[6];
var cidade = e.values[7];
var estado = e.values[8];
var cep = e.values[9];
var celular = e.values[10];
//seller info
var nome_vendedor = e.values[11];
var cpf_vendedor = e.values[12];
//template is the template file, and you get it by ID
var template = DriveApp.getFileById('1VB5u4OrqIQO8P6scj-rzkjtRlZ8NI-ZKd9xGKfnEqBA');
//acess main folder
var mainfolder = DriveApp.getFolderById('1G6g2VyrvpKpqSvLei3_jefQMNsGb-be0');
//create a new folder
var newFolderId = mainfolder.createFolder(nome + ' ' + cpf).getId();
//get new folder Id
var id = DriveApp.getFolderById(newFolderId);
//copy the template file to the new folder
var copy = template.makeCopy(nome + ' ' + cpf, id);
//open the document by it's Id
var document = DocumentApp.openById(copy.getId());
//get to the doc body for the replace
var body = document.getBody();
////////////
////////////
////////////
////////////
////////////
//ReplaceText methods
////////////
////////////
////////////
////////////
//client info
body.replaceText('{{nome}}', nome);
body.replaceText('{{cpf}}', cpf);
body.replaceText('{{rg}}', rg);
body.replaceText('{{rua}}', rua);
body.replaceText('{{numero}}', numero);
body.replaceText('{{bairro}}', bairro);
body.replaceText('{{cidade}}', cidade);
body.replaceText('{{estado}}', estado);
body.replaceText('{{cep}}', cep);
body.replaceText('{{celular}}', celular);
//seller info
body.replaceText('{{nome_vendedor}}', nome_vendedor);
body.replaceText('{{cpf_vendedor}}', cpf_vendedor);
//save and close the document
document.saveAndClose();
}
The easiest way to export a Goolge Document to pdf is using the UrlFetchApp
You need the
basic export url
the file id
specofy export parameters if and as required
An access token that you can obtain with the ScriptApp
Sample snippet based on you code before where you already have the document id:
var url = "https://docs.google.com/document/d/"+id+"/export?";
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+'&top_margin=0.50'
+'&bottom_margin=0.50'
+'&left_margin=0.50'
+'&right_margin=0.50'
// other parameters if you need
/*
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false' // hide page numbers
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
*/
var response = UrlFetchApp.fetch(url + url_ext,
{
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
muteHttpExceptions:true
});
DriveApp.createFile(response.getBlob().setName("myPdf"));

SaveAs .rgba file extention

I'm trying to do automate my file saving to saveAs file .rgba in photoshop. So far I only manage to modify the code to save out .sgi files. Please help. Thanks
var Name = app.activeDocument.name.replace(/\.[^\.]+$/,'');
var Path = app.activeDocument.path;
var saveFile = File(Path + "/" + Name +".sgi");
var saveFile2 = File(Path + "/" + Name +".rgba");
if(saveFile2.exists)
{
saveFile2.remove();
}
rgbaSaveOptions = new SGIRGBSaveOptions();
activeDocument.saveAs(saveFile, rgbaSaveOptions, true, Extension.LOWERCASE);
saveFile.rename(Name+'.rgba');

Unable to receive parameter in query string when redirected to other page

Hi I am developing one application in java-script. I have two pages default.aspx and addnewitem.aspx. there is one html table in default.aspx and one button. When i click on button i want to redirect to addnewitem.aspx page. I have some parameters to send in query string. I am able to redirect to addnewitem.aspx but page not found error i am getting. I am not sure why i am getting page not found error. I am trying as below.
function getValues() {
var Title = "dfd";
var PrimarySkills = "fdfd";
var SecondarySkills = "dfdf";
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=" + encodeURIComponent($(Title)) + "&PrimarySkills=" + encodeURIComponent($(PrimarySkills)) + "&SecondarySkills=" + encodeURIComponent($(SecondarySkills));
window.location.href = url;
}
I am checking querystring in addnewitem.aspx as below.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["Title"] != null && queryString["PrimarySkills"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Title:</b> " + queryString["Title"] + " <b>PrimarySkills:</b> " + queryString["PrimarySkills"] + " <b>SecondarySkills:</b> " + queryString["SecondarySkills"];
$("#lblData").html(data);
alert(data);
}
});
</script>
"http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=%5Bobject%20Object%5D&PrimarySkills=%5Bobject%20Object%5D&SecondarySkills=%5Bobject%20Object%5D"
I tried lot to fix this. May i know where i am doing wrong? Thanks for your help.
You should use the relative path in your url instead of hard coding the entire folder structure, which is probably incorrect since you are getting a 404. And you need to change the url every time you publish the site to the hosting enviroment when you hard code it like that.
So change
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=...
into
var url = "/AddNewItem.aspx?Title=...
if both the pages are in the same folder. Should AddNewItem.aspx be located in the Pages folder, you have to add that folder of course: var url = "/Pages/AddNewItem.aspx?Title=...

Need InDesign script to run on file open

I have this javascript that saves a copy of a file. I need it to run automatically every time a file is opened and also save that copy to a specific folder. Here's what I have so far:
var myDoc = app.activeDocument;
myDoc.save();
var myFile = myDoc.fullName;
var myDate = new Date;
var mySuffix = "_Backup_" + myDate.getDate() + "_" + myDate.getMonth() + "_" + myDate.getHours() + "-" + myDate.getMinutes() + "-" + myDate.getSeconds() +".indd"
var myBaseName = myDoc.fullName.fsName.match(/(.*)\.[^\.]+$/)[1] ;
var myNewFile = new File(myBaseName + mySuffix);
myFile.copy(myNewFile);
So what you want is called an event listener. (See the section "Working with event listeners" in the InDesign scripting guide.)
Save your .jsx file in the "startup scripts" folder. (On a Mac, it's in /Applications/Adobe InDesign CS6/Scripts/startup scripts/.)
#targetengine "session"
app.addEventListener('afterOpen', function(myEvent) {
// afterOpen fires twice: once when the document opens
// and once when the window loads. Choose one,
// ignore the other.
// See: http://forums.adobe.com/message/5410190
if (myEvent.target.constructor.name !== 'Document') {
return;
}
var myDoc = myEvent.target;
// Continue on with your code from here
}

Categories

Resources