Google Drive REST API - Update File Content - javascript

I would like to build an "Agreement Generator" for my business that is based on Google Docs Templates. I have a Node.js app that calls the Google Drive REST API v3. Here's how I'd like to do it:
Get a Google Document's raw content
Replace every ${variable_name} with value in that raw content (value is provided from an HTML form)
Update the Google Document raw content
I have been wrapping my head over this for days and I just can't find out how to get a Google Document's raw content.
It seems that all I can get is metadata. Other than that, I was thinking of maybe using the drive.files.export() method to get a Word document (to keep formatting and layout) then read it with Node and replace the values. But then I would have to re-upload that Word file and manually re-convert it to a Google Document from the Drive UI.
So I'm stuck there! Has anybody ever done something like that? Please help :)

Related

Is there a way to get a single response from a text/event-stream without using event listeners?

I'm writing a script in Google Sheets to retrieve a value from an API. The API provides text/event-stream responses ~every 10 seconds. Is there a way I can retrieve a single response without using async functions or event listeners? I'm not very competent in JavaScript, but because I'm working in Google Sheets, it seems like async functions and event listeners won't work properly. From what I've learned so far, the only way to work with text/event-stream responses is to use EventSource but I can't make it work with Google Sheets.
My goal is just to retrieve one response from the endpoint though, so any way I can accomplish that in Google Sheets would be great. Here is the endpoint in case that helps:
https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4
Because I was unable to use EventStream in Google Sheets, I tried using a polyfil found here: https://github.com/amvtek/EventSource/blob/master/dist/eventsource.js
and then running it with:
function getRplantTotal() {
var source = new EventSource('https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4');
source.addEventListener("message", function(e) {
console.log(e.data);
});
}
but this just outputs:
3:11:49 PM Notice Execution started
3:11:49 PM Notice Execution completed
I believe your goal is as follows.
You want to retrieve the 1st values from the URL of https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4 using Google Apps Script and want to use the retrieved values at Google Spreadsheet.
Issue and workaround:
When I saw https://github.com/amvtek/EventSource/blob/master/dist/eventsource.js, it seems that the request is run with XMLHttpRequest. At Google Apps Script, UrlFetchApp is used, and XMLHttpRequest cannot be used. I thought that this might be the reason for your current issue. But unfortunately, in the current stage, this cannot use text/event-stream type at Google Apps Script. When your URL is requested with UrlFetchApp, it looks like the infinite loop. This is the current situation.
So, from My goal is just to retrieve one response from the endpoint though, so any way I can accomplish that in Google Sheets would be great. and the above situation, I would like to propose a workaround. When you are running your script on Google Spreadsheet, how about retrieving the value from the URL using Javascript? Google Apps Script can retrieve the values from Javascript side using a dialog and a sidebar. From your question, when Javascript is used, the value can be retrieved. I thought that this might be able to be used. When this workaround is reflected in the Google Apps Script, it is as follows.
Sample script:
Google Apps Script side: Code.gs
Please copy and paste the following script to the script file of the script editor of Google Spreadsheet.
// Please run this function.
function main() {
SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile("index"), "sample");
}
function getValues(e) {
const obj = JSON.parse(e); // This is the 1st value from the URL of "https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4"
console.log(obj)
// DriveApp.createFile("sample.txt", e); // When you use this, the retrieved value can be created as a text file.
}
Javascript side: index.html
Please copy and paste the following script to the HTML file of the script editor of Google Spreadsheet. Please set the filename as index.html.
Values are retrieving now. Please wait. After the values were retrieved, this dialog is automatically closed.
<script>
var source = new EventSource('https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4');
source.addEventListener("message", function(e) {
source.close();
google.script.run.withSuccessHandler(google.script.host.close).getValues(e.data);
});
</script>
In this script, please run main() function from the script editor. By this, a dialog is opened on the Spreadsheet and the values are retrieved from the URL using Javascript, and when the 1st values are retrieved, the values are sent to Google Apps Script side. So you can use the retrieved values at the function of getValues.
Note:
In this workaround, it is required to execute the script by the browser. Because Javascript is used. So, please be careful about this.
As another workaround, when you can use only Javascript, Sheets API can be used with Javascript. Ref In this case, the values can be also retrieved and put to the Spreadsheet using Javascript.
References:
Dialogs and Sidebars in Google Workspace Documents
Class google.script.run (Client-side API)

Render html (or html output) to Google Drive Docs(word) using javascript

I have an project where I have to render the html form output to an new google docs(word and NOT THE SPREADSHEET !) The only thing what I can find on the internet is about spreadsheet.
The project.
I have an html with form.
I need to get all the data in a new file in google docs when i click on submit.
Can someone show me a way how to solve this.
Hint Links etc etc.
Try following this code:
function myFunction() {
// Create and open a document.
// Replace with your own document name
var doc = DocumentApp.create('Document Name');
var pages = doc.getBody();
pages.appendPageBreak();
pages.appendParagraph("A paragraph.");
pages.appendPageBreak();//push additional data to the next page
pages.appendParagraph("A paragraph 2.");
}
This code will let you create a document and write in the pages. Also read Document Service, this service allows scripts to create, access, and modify Google Docs files. There are alot of features you can use to make your document more presentable.
Now, you connect your form to apps script. Just follow the steps done in this tutorial. Publish your code as web app, then use the web app URL to pass the variable to your script and save the data to the document.
Hope this helps.

Google Docs Spreadsheet to JSON

I've seen numerous articles on this but they seem outdated, for instance none of the Google Docs Spreadsheet urls has key parameter. I read this as well:
JSON data from google spreadsheet
Then I read this to access data
https://developers.google.com/gdata/samples/spreadsheet_sample
My spreadsheet exists at:
https://docs.google.com/spreadsheets/d/1SKI5773_68HiSve1fsz7fr4gotjFWHB7KBuVsOlLz6I/edit#gid=0
I've tried using this code, I think I have a problem with the key or syntax, please guide to fix.
<script src="http://spreadsheets.google.com/feeds/feed/1SKI5773_68HiSve1fsz7fr4gotjFWHB7KBuVsOlLz6I/worksheet/public/basic?alt=json-in-script&callback=importGSS"></script>
<script type="text/javascript">
function importGSS(json) {
console.log('finished');
}
</script>
The src attribute in your script tag is an invalid link (and you can see this for yourself by viewing your link directly in a browser).
The feed/key/worksheet section of the URL has the right key but the wrong feed and worksheet.
In the URL, replace "feed" with either "cells" (separate value for each cell) or "list" (separate value for each row).
At the same time, replace "worksheet" with "od6" (indicating the leftmost, or default, sheet - see this blog post for accessing other sheets).
If you view this new URL directly in a browser, you can see that it returns a meaningful value.
Your final script tag might look like this:
<script src="https://spreadsheets.google.com/feeds/list/1SKI5773_68HiSve1fsz7fr4gotjFWHB7KBuVsOlLz6I/od6/public/values?alt=json-in-script&callback=importGSS"></script>
For more info, you can see an example on the Google Developers site
APISpark PaaS has a feature to create and deploy a custom JSON API based on a GSpreadsheet. That might help and give you more control on the web API (CORS support, authentication, custom domain and so on).
See the tutorial here: https://apispark.com/docs/tutorials/google-spreadsheet
You may consider use an alternative to this request of your sheet data, because this method is deprecated.
Anyway, you can still using another feed format, you can see this alternatives in:
https://spreadsheets.google.com/feeds/worksheets/your-spreadsheet-id/private/full
In that result you can see any export formats are availables. Can help you an CSV or alt JSON visualization format?
Another potential solution here is to use this https://gist.github.com/ronaldsmartin/47f5239ab1834c47088e to wrap around your existing spreadsheet.
Add the id and sheet html param to the URL below.
https://script.google.com/macros/s/AKfycbzGvKKUIaqsMuCj7-A2YRhR-f7GZjl4kSxSN1YyLkS01_CfiyE/exec
Eg: your id is your sheet id which is
1SKI5773_68HiSve1fsz7fr4gotjFWHB7KBuVsOlLz6I
and your sheet which is
Sheet1
In your case you can actually see your data (it's actually working) here as json at
https://script.google.com/macros/s/AKfycbzGvKKUIaqsMuCj7-A2YRhR-f7GZjl4kSxSN1YyLkS01_CfiyE/exec?id=1SKI5773_68HiSve1fsz7fr4gotjFWHB7KBuVsOlLz6I&sheet=Sheet1
To be safe, you should deploy the code sheetAsJson.gs in the github gist above as your own in your Google Drive.
You have plenty of possible answers above. For those that come anew, if you're looking for a more controlled JSON generator, check out this gist:
JSONPuller
It takes in a Spreadsheet and returns an array of objects, with the lined that you decide as the headers (defaults to whichever line is frozen)
Cheers,
The easiest way for me was to export spreadsheet to CSV
File -> Download -> Comma-separated values
Then just convert CSV to JSON with free online servic

Writing a custom file format downloader in Google Spreadsheets

What I'm aiming to do is write something akin to the File > Download as > * functionality currently in Google Spreadsheets, but I want it to be in a custom format.
Specifically, I want to turn a spreadsheet of financial transactions into an QIF or OFX file for importing into accounting software. In essence, pushing a button on the UI will download a QIF/OFX version of the currently open spreadsheet.
I have tried the following so far:
Publishing a service (via implementing doGet) that uses ContentService to create the custom file and return it as a download using TextOutput.downloadAsFile(). This works if I call the endpoint directly using my browser.
Tried redirecting the browser to the Service's URL via window.location, but that doesn't seem to be available in the context of the App Script.
Tried using UrlFetchApp.fetch to have the front-end (the spreadsheet) have the browser navigate to the URL for the service. This didn't work either (not really surprising).
So, is this the right approach here? How else can I attack this?
Looks like this is what you have to do.
Create a UiApp
Add a link to the download inside that app.
Show the UiInstance on the spreadsheet
It's a little bit bulky, but it seems the be the cleanest solution.
function downloadAsWhatever() {
var app = UiApp.createApplication();
app.add(app.createAnchor("Download the file now!", "https://script.google.com/macros/s/[...]/exec"))
SpreadsheetApp.getActiveSpreadsheet().show(app.setWidth(300).setHeight(150));
}
You can set the size of the app to whatever you'd like. I chose to set it smaller so it takes up less space on the Spreadsheet screen.
For now the best way to direct a user to a new page is to create an anchor widget and have them click it. We understand that this is not an ideal user experience, but it should suffice for must use cases.
Source

Google spreadsheet with hyperlinks via JSON

I'm using json-in-script to put content from a Google Spreadsheet on a web page. The spreadsheet has hyperlinks on some of the text in the cells. JSON doesn't seem to be getting anything other than the plain text of the spreadsheet, and no markup like hyperlinks. How do you get hyperlinks? Can you with JSON?
This is the src of what I'm importing:
http://spreadsheets.google.com/feeds/cells/0Aipg92XowKCndHhtbnZXQkllWEUzUjBEc3NkQXppdnc/1/public/values?alt=json-in-script&callback=cellEntries&min-row=2&min-col=1&max-col=7
This is the link to the spreadsheet (see how the items in col1 are linked?)
https://spreadsheets.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0Aipg92XowKCndHhtbnZXQkllWEUzUjBEc3NkQXppdnc&output=html
Can anyone advise me how to get the hyperlinks?
Thanks!
You'll want to do some post-processing, checking if a value matches a URL. If it does, create your own tag for it.
Use one of these:
http://www.google.com/search?q=url+regex
Also, you know that you can embed Google Spreadsheets directly in a webpage? I'm guessing you're not doing this because it would use an iFrame, and what you want is the actual data?
Rather than using the Google Speadsheets API (which is quite cumbersome), you should use jsondata.com. It'll let you upload all the data from a .csv and embed it in your site with YouTube-style embed code.
The post processing is a piece of cake when you get your entire dataset to your application in a nicely formatted JSON object.

Categories

Resources