Save Document without closing - google-apps-script

How do I save the current document as docx without closing through saveAndClose() first? I want to create multiple docx files from the same original Google Docs document on which my Script is running.

You can export a docs to docx with URL fetch:
function myFunction() {
var doc_id = 'YOUR DOCUMENT ID';
var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' + doc_id + '&exportFormat=docx';
var options = {
headers: {
Authorization: "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(url, options);
var doc = response.getBlob();
DriveApp.createFile(doc).setName('myDocxFile1');
DriveApp.createFile(doc).setName('myDocxFile2');
}

Related

Get the blob of a drive file using Drive api

I used below script to get the blob of abc.dat file which is generated via my Apps Script project. With the Drive service, it is easy.
Used oauthScope is https://www.googleapis.com/auth/drive.readonly
function ReadData() {
var files;
var folders = DriveApp.getFoldersByName("Holder");
if (folders.hasNext()) {
var folder = folders.next();
var files = folder.getFiles();
while (files.hasNext()){
file = files.next();
if(file.getName()=='abc.dat'){
var content = file.getBlob().getDataAsString();
return content;
}
}
}
return '';
}
In order to reduce the authentication scope, Now I am modifying the code to fully remove the https://www.googleapis.com/auth/drive.readonly oauthScope and use only the https://www.googleapis.com/auth/drive.file oauthScope.
Using the Drive api, I didn't found a direct way to get the blob of a file.
I used this below script to get the blob of a word document file. But it is not working for the .dat file with error fileNotExportable, Export only supports Docs Editors files, code 403
function getBlob(fileID, format){
var url = "https://www.googleapis.com/drive/v3/files/" + fileID + "/export?mimeType="+ format;
var blob = UrlFetchApp.fetch(url, {
method: "get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
}).getBlob();
return blob;
}
Found this article and tried changing the export with get in the url. The returning blob.getDataAsString() gives "Not found" now.
The mimeType I used when creating the abc.dat file is application/octet-stream .dat. But when check the generated file, its mimeType is text/plain. So I used the 'text/plain' as the input for 'format' parameter in getBlob function.
.dat file creation code :
var connectionsFile = {
title: filename,
mimetype: "application/octet-stream .dat",
parents: [{'id':folder.getId()}],
};
var blobData = Utilities.newBlob(contents);
file = Drive.Files.insert(connectionsFile,blobData);
}
How can I modify this code to get the blob from the file? or is there any other way around?
Thanks in advance!
I think that in your situation, it is required to use get method instead of export method. Because export method is used for Google Docs files (Document, Spreadsheet, Slides and so on). When your script is modified, how about the following modification?
Modified script:
function getBlob(fileID) {
var url = "https://www.googleapis.com/drive/v3/files/" + fileID + "?alt=media";
var blob = UrlFetchApp.fetch(url, {
method: "get",
headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
}).getBlob();
return blob;
}
Reference:
Download files

update google sheet script with another script

I have a folder with approximately 140 google sheets and a main standalone google script that I call with a library script from each sheet but need to add/update all of the scripts attached to each google sheet script. Currently the only way I have found is to open each sheet script and add the library script save and move on but 140 sheets takes a long time. I know all my sheets that i need scripts adding or updating are in one folder so thinking I could use something like this to loop through all the gsheets but can't find away to edit the scripts from here...
function scriptupdate() {
var folder = DriveApp.getFolderById('FOLDER CONTAINING THE GSHEETS ID');
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log("File Name is "+file.getName());
Logger.log("File ID is "+file.getId());
}
}
I'm not sure if what I'm trying to do is possible but trying to save a lot of time if this is doable but really appreciate any help and guidance offered
Answer
You can create and update projects and its content using the projects resource methods. As these have no built-in service in Apps Script they must be called with urlFetchApp.fetch.
When writing functions, remember to put them between grave accents (`). You can use the key combination Ctrl + Shift + I to fix all the indentation and spacing in the whole script file.
Code
function scriptupdate() {
// GET FILES
var folder = DriveApp.getFolderById('FOLDER CONTAINING THE GSHEETS ID');
var files = folder.getFiles();
while (files.hasNext()) {
// GET FILE INFORMATION
var file = files.next();
var name = file.getName()
var fileId = file.getId()
// CREATE CONTAINER-BOUND SCRIPT
var url = 'https://script.googleapis.com/v1/projects'
var formData = {
'title': name,
'parentId': fileId
};
var options = {
method: 'post',
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
payload: formData,
muteHttpExceptions: true
};
var res = JSON.parse(UrlFetchApp.fetch(url, options).getContentText())
var scriptId = res["scriptId"]
// UPDATE PROJECT CONTENT
var url = 'https://script.googleapis.com/v1/projects/' + scriptId + '/content';
var formData = {
"files": [
{
"name": "appsscript",
"type": "JSON",
"source": `{
"timeZone": "America/New_York",
"dependencies": {},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}`
},
{
"name": "main",
"source":
`function main() {
console.log('hello world')
}`,
"type": "SERVER_JS"
}
]
}
var options = {
method: 'put',
contentType: 'application/json',
payload: JSON.stringify(formData),
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
};
var res = UrlFetchApp.fetch(url, options).getContentText()
console.log(res)
}
}
Reference
projects
projects: create
projects: updateContent
urlFetchApp.fetch

Changing json file creation destination from dropbox to google drive

i need to have this code have the create the json file inside of google drive instead of drop box
I have experimented with a few things but i am not quite knowledgeable enough to make this change, i would show less code but i do not know where the problem lies
function main(spreadsheet_id) {
var json_dict = fillDict(spreadsheet_id)
var json_obj = convertDictToJSON(json_dict)
sendJSONToDropbox(json_obj)
};
function sendJSONToDropbox(json_object) {
var timestamp = timeStamp()
var parameters = {
"path": "/json_jobs/rhino" + "-" + timestamp + ".json",
"mode": "add", // do not overwrite
"autorename": true,
"mute": false // notify Dropbox client
};
var headers = {
"Content-Type": "application/octet-stream",
'Authorization': 'Bearer ' + 'dropbox_access_token',
"Dropbox-API-Arg": JSON.stringify(parameters)
};
var options = {
"method": "POST",
"headers": headers,
"payload": json_object
};
var API_url = "https://content.dropboxapi.com/2/files/upload";
var response = JSON.parse(UrlFetchApp.fetch(API_url, options).getContentText());
Using the DriveApp class, it is not too difficult:
function sendJSONToGDrive(json_object) {
var timestamp = timeStamp();
var fileName = "rhino" + "-" + timestamp + ".json";
var fileContent = JSON.stringify(json_object);
var myFolder = DriveApp.getFolderById('YOUR_FOLDER_ID');
myFolder.createFile(fileName, fileContent, 'application/json');
}
You just have to replace YOUR_FOLDER_ID for your actual destination folder's id.
For more information on how to use the Drive API from Google Apps Script, I recommend you check out the following link: https://developers.google.com/apps-script/reference/drive

Converting spreadsheet into microsoft excel using Google Apps, but not working

Used below code to convert spreadsheet into xlsx.
Though looks to be working fine, But doesn't works same as Microsoft Excel. Looking help on alternative to convert spreadsheet into microsoft xlsx file or Blob.
Objective:
I have an API that accepts only Microsoft .xlsx with data available in Google Spreadsheet; and hence trying to convert spreadsheet into Microsoft xlsx.
My Code:
function exportToXlsx(){
var fileId = "{{fileID_of_spreadsheet}}";
var targetFolderID = "{{target_folderID}}";
Logger.log("Input File ID: " + fileId);
try {
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + fileId + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
//set name to blob
blob.setName(DriveApp.getFileById(fileId).getName() + ".xlsx");
//create the xlsx file
var newFile = DriveApp.createFile(blob);
} catch (f) {
Logger.log(f.toString());
}
}

Sending Google Doc as HTML in email body using Google Apps Script while preserving format

Using the script below on a Google Doc, I'm trying to send the document as HTML in an email body. It's converting the document correctly (when I check the exported document via the url) and sending the email with the same content, but it loses the following formatting at some point: font format (e.g., size, color) and table format (e.g., borders, background color)
function sendGoogleDocAsHTML(){
var id = DocumentApp.getActiveDocument().getId() ;
var url = "https://docs.google.com/document/d/"+id+"/export?format=html"
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url, param);
var email = <EMAIL>;
var subject = <SUBJECT>;
GmailApp.sendEmail(email, subject,"", {htmlBody:html});
}
How do I preserve the format in the email?
This worked fine for me. Hope this may help
function sendGoogleDocAsHTML(){
var id = DocumentApp.getActiveDocument().getId() ;
var url = "https://docs.google.com/document/d/"+id+"/export?format=html"
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url, param);
var raw = Utilities.base64EncodeWebSafe("Subject: Test\r\n" +
"To: test#gmail.com\r\n" +
"Content-Type: text/html; charset=UTF-8\r\n\r\n" +
html+"\r\n\r\n");
var message = Gmail.newMessage();
message.raw = raw;
var sentMsg = Gmail.Users.Messages.send(message, 'me');
}