Export Google sheet as xlsx to company network drive - excel

This function is triggered when the sheet is changed.
function exportAsxlsx() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = spreadsheet.getId()
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var blobs = response.getBlob();
var folder = DriveApp.getFoldersByName('\\GBC1234.fs1.util.xxint.com\Shared\Projects\Test_Google2Excel');
if(folder.hasNext()) {
var existingPlan1 = DriveApp.getFilesByName('TestGoogle2Excel.xlsx');
if(existingPlan1.hasNext()){
var existingPlan2 = existingPlan1.next();
var existingPlanID = existingPlan2.getId();
Drive.Files.remove(existingPlanID);
}
} else {
folder = DriveApp.createFolder('\\GBC1234.fs1.util.xxint.com\Shared\Projects\Test_Google2Excel');
}
folder = DriveApp.getFoldersByName('\\GBC1234.fs1.util.xxint.com\Shared\Projects\Test_Google2Excel').next();
folder.createFile(blobs).setName('TestGoogle2Excel.xlsx')
}
What happens is that it makes the directory "\GBC1234.fs1.util.xxint.com\Shared\Projects\Test_Google2Excel" in Google drive then saves the file there.
How can I get it to save to our company drive?

You will need to have a locally hosted 'client' which downloads said file from the known drive location to the network.
Once you start thinking about this the client could interact with a number of points on the workflow you describe.
I.e.
1. As described, polls google drive to see if output xlsx is created and download. Drive API
2. Poll the sheet in drive itself and also then trigger the apps script to perform conversion. Apps Script Execution API
3. Skip those altogether and interact with the sheet directly. Sheets API
In each case you'll want to cache a checksum of the original sheet data to only act if things have changed. (There are a number of ways to do this)

Related

How do I copy data from an xlsx file in my google drive to a google sheet?

I have an excel file (.xlsx) saved on my google drive. I want to copy the data from there into a tab in a google sheet file i have already created. I have the following code that runs. But I don't know exactly how to specify the Google Sheet (and tab) to paste the excel data in?
``
function run() {
try {
fileName = fileName || "G:\Shared drives\ExchangeData\DailyVolumes.xlsx";
var excelFile = DriveApp.getFilesByName(fileName).next();
var fileId = excelFile.getId();
var folderId = Drive.Files.get(fileId).parents[0].id;
var blob = excelFile.getBlob();
var resource = {
title: excelFile.getName().replace(/.xlsx?/, ""),
key: fileId
};
Drive.Files.insert(resource, blob, {
convert: true
});
} catch (f) {
Logger.log(f.toString());
}
}
You want to copy the values of ".xlsx" file to the existing Google Spreadsheet.
There is the ".xlsx" file in your Google Drive.
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 order to retrieve the values from the Google Spreadsheet converted from the ".xlsx" file, it uses the file ID returned from Drive.Files.insert().
In your script, it is required to declare the destination Google Spreadsheet which copies the values from the ".xlsx" file and to use it.
Modified script:
When your script is modified, please modify as follows. Before you run the script, please set the variables of destSpreadsheetId and destSheetName.
From:
fileName = fileName || "G:\Shared drives\ExchangeData\DailyVolumes.xlsx";
var excelFile = DriveApp.getFilesByName(fileName).next();
var fileId = excelFile.getId();
var folderId = Drive.Files.get(fileId).parents[0].id;
var blob = excelFile.getBlob();
var resource = {
title: excelFile.getName().replace(/.xlsx?/, ""),
key: fileId
};
Drive.Files.insert(resource, blob, {
convert: true
});
To:
var destSpreadsheetId = "###"; // Added
var destSheetName = "###"; // Added
fileName = fileName || "G:\Shared drives\ExchangeData\DailyVolumes.xlsx";
var excelFile = DriveApp.getFilesByName(fileName).next();
var fileId = excelFile.getId();
// var folderId = Drive.Files.get(fileId).parents[0].id; // This is not used in your script.
var blob = excelFile.getBlob();
var resource = {title: excelFile.getName().replace(/.xlsx?/, "")}; // Modified
var sourceSpreadsheet = Drive.Files.insert(resource, blob, {convert: true}); // Modified
// Also I added below script.
var sourceSheet = SpreadsheetApp.openById(sourceSpreadsheet.id).getSheets()[0];
var destSheet = SpreadsheetApp.openById(destSpreadsheetId).getSheetByName(destSheetName);
var values = sourceSheet.getDataRange().getValues();
destSheet.getRange(destSheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
Note:
In your question, I'm not sure whether the ".xlsx" file has several sheets and the range you want to put the values. So in this modification, as a sample, the values of the 1st tab in the converted Spreadsheet are copied to the last row in the destination Spreadsheet.
In this modified script, it supposes that you have already enabled Drive API at Advanced Google services.
References:
Files: insert
openById(id)
getSheets()
getDataRange()
getValues()
setValues(values)
If I misunderstood your question and this was not the direction you want, I apologize.

How to convert specific Google Spreadsheet to Excel?

Dear 'Google APPS Script' Experts,
I need a script to convert a specific Google Spreadsheet and overwrite an Excel file (.xlsx) within Drive (same drive folder). I have a script to do this the other way around. I tried to change the script to make it work and searched on the internet to find a script but the ones I found did not work. I have no programming knowledge in this area so hope someone can help me with this.
The script to do this the other way around, many thanks to the script expert who shared this, looks like....
function convertExceltoGoogleSpreadsheet(fileName) {
var dstFileId = '1dL8MbCKdoWFcV8............etc';
fileName = fileName || 'Conversie_Test.xlsx'; // excel_file_name.xlsx = name of specific Excel file
var excelFile = DriveApp.getFilesByName('Conversie_Test.xlsx').next();
var fileId = excelFile.getId();
var srcFileId = fileId; // file Id of Excel file
Drive.Files.update({}, dstFileId, DriveApp.getFileById(srcFileId))
}
Hope someone can help me out on this.
Best regards,
Marco
Answer:
You can use the export method of Drive to export a Sheet as an Excel file and insert it into Drive using the Advanced Drive Service.
Prerequisites:
Make sure you have enabled the Advanced Drive service by going to Resources > Advanced Google Services, scrolling down to Drive API and while making sure that v2 is selected in the dropdown, clicking the slider on the right hand-side so that instead of 'off' it turns green and switches to 'on'.
Code:
function convertSheetToXlsx() {
var ssID = "<your-spreadsheet-id>";
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=";
var exportMethod = "&exportFormat=xlsx";
var parameters = {
method: "get",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
};
var fileAsBlob = UrlFetchApp.fetch(url + ssID + exportMethod, parameters).getBlob();
fileAsBlob.setName(SpreadsheetApp.openById(ssID).getName() + ".xlsx");
var fileData = {
title: SpreadsheetApp.openById(ssID).getName() + ".xlsx",
mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
};
Drive.Files.insert(fileData, fileAsBlob);
}
References:
Google Sheets API Documentation
Advanced Drive Service

Transfer data in Excel attachment, in Outlook or Gmail, to Google sheet

I daily receive an email in Outlook with an Excel sheet attached.
I am working with dashboard/templates in Google data studio, and Google sheets. To make this work smoothly, I need to transfer the data from the Excel sheet to my Google sheet automatically. Is this possible?
My first thought was to send the attached Excel sheets to my gmail instead, because from here I could write a script that gets the data from the gmail. This was more complicated than I thought.
Maybe a VBA code to transfer the attached Excel file to google-drive, and then from there I could update my Google sheet? Is this possible?
Note: I am not experienced enough to write VBA/APP script from scratch.
Q: The OP asks: is it possible to transfer an Excel spreadsheet, received as an Outlook attachment, to google-drive, and then update it to a Google Sheet format?
A: Yes.
Q: What are the discrete steps required to satisfy the OP's objective?
A:
1 - Write a macro in Outlook to automatically forward the email and Excel attachment to the OP's GMail account; specifically to the account used to log into Google Sheets. For the purposes of this answer this aspect, though fairly straightforward, this is treated as off topic.
2 - Create a folder (or folder/subfolder) in Google Drive where the Excel spreadsheet can be saved. This could be done manually or by script. "Manually" is easier, "by script" is more fun and offers more flexibility.
3 - Run a Google script to access the OP's Gmail account, identify Excel attachments (say, files ending with 'xls', 'xlsx', 'xlsm' - other variations can be added), and save the Excel file to the Google Drive folder. Attach a "label" to each relevant email so that only new unprocessed messages are processed.
4 - Run a Google script to access the Google Drive folder/subfolder and convert the Excel spreadsheet to a Google Sheet.
As noted in comments, this topic has been raised, in one form or another, many times before: Is there any google API which could save gmail message attachments to google drive? and Convert all xls files available in a folder into “Google Doc Spreadsheets”? are two good examples. Google search will reveal many other topics - on StackOverflow and other sources.
However Google services (Docs, scripts, APIs, etc) are being constantly enhanced. One of the by-products of this development is that some methods are discontinued and this can render a previously correct answer to become out-of-date.
Unfortunately this is the case with the excellent GmailToDrive() function supplied in the Jan 2018 answer to Is there any google API which could save gmail message attachments to google drive?. Google Advanced Drive Service and Drive API changed during 2018 and that excellent answer now falls at the last hurdle.
The following code is supplied in order to provide an update to February 2019.
The basis of this answer is the GmailToDrive() function provided by Mr.Rebot, but modified for Excel files.
Trigger
The code should be set as a time-driven, Installable Trigger. The frequency will vary from case to case. The OP can make their own assessment. There are other sources that are available to explain this.
Drive API
The OP must activate the Drive API (Advanced Services as well as the Google Cloud Platform API Dashboard). For the sake of clarity, a brief outline of the steps is at the end of this answer.
Code
// GLOBALS
// Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['xls', 'xlsx', 'xlsm'];
//Name of the folders in google drive in which files will be put
var homeFolder = "009-StackExchange"; // a folder branching from the root
var ExcelFolderName = "010-GmailToDrive"; // sub folder of "homeFolder"
//Name of the label which will be applied after processing the mail message
var emaillabelName = 'GmailToDrive';
function so54755021()
// an adaptation of function GmailToDrive()
{
//build query to search emails
var query = '';
// loop through the filestoextract and add to query
for (var i in fileTypesToExtract) {
query += (query == '' ? ('filename:' + fileTypesToExtract[i]) : (' OR filename:' + fileTypesToExtract[i]));
}
//Logger.log("DEBUG: #01 the query is: " + query); //DEBUG
query = 'in:inbox has:nouserlabels ' + query;
//Logger.log("DEBUG: #02 the query is: " + query); //DEBUG
var threads = GmailApp.search(query);
//Logger.log("DEBUG: threads = " + threads + "; threads length = " + threads.length); //DEBUG
var label = getGmailLabel_(emaillabelName);
//Logger.log("DEBUG: label = " + label); //DEBUG (GmailToDrive)
var parentFolder;
if (threads.length > 0) {
//Logger.log("DEBUG: threads length is more than zero");//DEBUG
//Logger.log("DEBUG: folder name = " + folderName); //DEBUG
//parentFolder = getFolder_(folderName); // subroutine
// build sub-folder if necessary
createDriveFolder(homeFolder, ExcelFolderName);
parentFolder = homeFolder;
}
for (var i in threads) {
var mesgs = threads[i].getMessages();
for (var j in mesgs) {
//get attachments
var attachments = mesgs[j].getAttachments();
for (var k in attachments) {
var attachment = attachments[k];
//Logger.log("DEBUG: attachment: " + attachment);//DEBUG
var isExcelType = checkIfExcel_(attachment);
//Logger.log("DEBUG: isExceltype = " + isExcelType);//DEBUG
if (!isExcelType) continue;
// Copy the Blob
var attachmentBlob = attachment.copyBlob();
//Logger.log("DEBUG: attachmentblob = " + attachmentBlob);//DEBUG
var ExcelFolderObject = DriveApp.getFoldersByName(ExcelFolderName).next();
//Create the Excel file in Google Drive
var file = ExcelFolderObject.createFile(attachmentBlob);
// get the file name and ID
var fileid = file.getId();
var filename = file.getName();
// Logger.log("DEBUG: file = " + file + ", and ID = " + fileid + ", and file name: " + filename);//DEBUG
var fileType = file.getMimeType()
// Logger.log("DEBUG: the MIME type is " + fileType);//DEBUG
// copy the Blob again in preparation for conversion
var xBlob = file.getBlob();
// get the folder ID to copy the file
var folderId = DriveApp.getFoldersByName(ExcelFolderName).next().getId();
// set parameters for the new file
var newFile = {
title: filename + '_converted',
key: fileid,
parents: [{
"id": folderId
}]
}
// convert the file
var convfile = Drive.Files.insert(newFile, xBlob, {
convert: true
});
// Logger.log("DEBUG: the converted file is " + convfile);//DEBUG
}
}
// Add the label to the Gmail item
threads[i].addLabel(label);
}
}
// If necessary, create the label in GMail
function getGmailLabel_(name) {
var label = GmailApp.getUserLabelByName(name);
if (label == null) {
label = GmailApp.createLabel(name);
}
return label;
}
function createDriveFolder(baseFolder, folderName) {
var baseFolderObject = DriveApp.getFoldersByName(baseFolder).next();
//Logger.log("DEBUG: basefolderobject = " + baseFolderObject);//DEBUG
var folders = DriveApp.getFoldersByName(baseFolder).next().getFolders();
//Logger.log("DEBUG: folders: "+folders);//DEBUG
// set variable to detect a match
var foldermatch = 0;
//Loop through folders
while (folders.hasNext()) {
var folder = folders.next();
//Logger.log(DEBUG: folder.getName());//DEBUG
// If the folder name matches
if (folder.getName() == folderName) {
// update the match variable
foldermatch = 1;
// Logger.log("DEBUG: there's a match/folder exists: " + folder.getName());//DEBUG
}
}
// Do something is there is a match
if (foldermatch != 0) {
//Logger.log("DEBUG: There was a match so do NOTHING");//DEBUG
} else {
// Logger.log("DEBUG: There was no match so create the folder"); //DEBUG
baseFolderObject.createFolder(folderName);
}
// The folder already existed, or it has been created. Either way, our work is done.
return;
}
// this function will check for filextension type.
// and return boolean
function checkIfExcel_(attachment) {
var fileName = attachment.getName();
var temp = fileName.split('.');
var fileExtension = temp[temp.length - 1].toLowerCase();
if (fileTypesToExtract.indexOf(fileExtension) != -1) return true;
else return false;
}
Enable the Drive Api
1 - From the Script Editor, select Resources > Advanced Google Services; select Drive API and slide the switch to On.
2 - Click the link to the "Google Cloud Platform API Dashboard"
3 - The Google Cloud Platform - APIs and Services screen opens in a new window.
Click the link to Enable APIs and Services
4 - Search for "drive", and then click the option for Drive API.
5 - Click the "Enable" button for the Drive API
6 - The system will display the Drive API details; note the Drive API is enabled. Then just close this window.
7 - Click OK on the "Advances Google Services" screen (which has remained open all this time).
You're ready to run the script.

How to copy postman history from chrome app to native app?

Since Google is now ending the support for chrome apps. Recently Postman deprecated their chrome app and introduced a native app.
I am in the process of switching from postman chrome app to native app.
How do I copy the history from my chrome app to native app. Sync doesn't work.
There is a option to export data but that doesn't export the history.
Any Ideas?
So while searching for this I came across this post which is very helpful.
Thanks to stephan for sharing this code.
Follow these steps to copy your history from chrome app to native app.
//In Chrome DevTools on the background page of the Postman extension...
//A handy helper method that lets you save data from the console to a file
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
//Common error reporting function
function reportError(){
console.error('Oops, something went wrong :-(');
}
//Open the database
var dbReq = indexedDB.open('postman')
dbReq.onerror = reportError;
dbReq.onsuccess = function(){
var db = dbReq.result;
//Query for all the saved requests
var requestReq = db.transaction(["requests"],"readwrite").objectStore('requests').getAll();
requestReq.onerror = reportError;
requestReq.onsuccess = function(){
var requests = requestReq.result;
//Dump them to a file
console.save(JSON.stringify(requests), 'postman-requests-export.json')
console.info('Your existing requests have been exported to a file and downloaded to your computer. You will need to copy the contents of that file for the next part')
};
};
//Switch to standalone app and open the dev console
//Paste the text from the exported file here (overwriting the empty array)
var data = []
//Enter the guid/id of the workspace to import into. Run the script with this value blank if you need some help
// finding this value. Also, be sure you don't end up with extra quotes if you copy/paste the value
var ws = '';
//Common error reporting function
function reportError(){
console.error('Oops, something went wrong :-(');
}
//Open the database
var dbReq = indexedDB.open('postman-app')
dbReq.onerror = reportError;
dbReq.onsuccess = function(){
var db = dbReq.result;
if(!data.length){
console.error('You did not pass in any exported requests so there is nothing for this script to do. Perhaps you forgot to paste your request data?');
return;
}
if(!ws){
var wsReq = db.transaction(["workspace"],"readwrite").objectStore('workspace').getAll();
wsReq.onerror = reportError;
wsReq.onsuccess = function(){
console.error('You did not specify a workspace. Below is a dump of all your workspaces. Grab the guid (ID field) from the workspace you want these requests to show up under and include it at the top of this script');
console.log(wsReq.result);
}
return;
}
data.forEach(function(a){
a.workspace = ws;
db.transaction(["history"],"readwrite").objectStore('history').add(a);
});
console.log('Requests have been imported. Give it a second to finish up and then restart Postman')
}
//Restart Postman
Note :
1.To Use DevTools on your chrome app you will need to enable following flag in
chrome://flags
2.Then just right click and inspect on your chrome postman app.
3.To User DevTools on your native app ctrl+shift+I (view->showDevTools)

Windows 10 App - File downloading

I am working with Windows 10 universal app and i want to download a file in that. The file link to Sharepoint server. I have passed token in headr to a web service and then service returned byte array to my WinJS.
Now i want to save the file, how can i do this? I tried several code samples but not working.
var folder = Windows.Storage.ApplicationData.current.localFolder;
folder.createFileAsync("document.docx", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file, result.response);
}).then(function () {
//saved
});
I am using above code and it is creating new file but no content is placed there. Please suggest what to do.
You never open the file for WriteAccess. I have included code from my working app. First do this command
StorageFile ageFile = await local.CreateFileAsync("Age.txt", CreationCollisionOption.FailIfExists);
then do this:
// Get the file.
var ageFile = await local.OpenStreamForWriteAsync("Age.txt",CreationCollisionOption.OpenIfExists);
// Read the data.
using (StreamWriter streamWriter = new StreamWriter(ageFile))
{
streamWriter.WriteLine(cmbAgeGroup.SelectedIndex + ";" + DateTime.Now);
streamWriter.Flush();
}
ageFile.Dispose();

Resources