I have a google spreadsheet with processed data nice graphs that can be updated with different source data.
I have a script that can create a google document from a template and populate it with data (with search and replace).
However, I like to add the graphs from the google spreadsheet to the google document.
I've been googling a lot, but can't find a script that I can use/modify to pull of this thing.
A basic start would be highly appreciated.
Update:
I've made some progress
function test() {
SpreadsheetApp.flush();
var Grafieken = SpreadsheetApp.getActiveSheet().getCharts();
var targetDoc = DocumentApp.openById(anID);
var DBody = targetDoc.getBody();
for (var i in Grafieken) {
var Grafiek = Grafieken[i];
var plaatje = DBody.appendImage(Grafiek);
}
However I encountered two issues:
- most importantly, the graphs do not look like in the spreadsheet
- not all the graphs are added (e.g. mixed diagrams are skipped)
UPDATE2
This almost works, I need to know which graph is which.
function test() {
SpreadsheetApp.flush();
var Grafieken = SpreadsheetApp.getActiveSheet().getCharts();
var targetDoc = DocumentApp.openById(DOC_id);
var DBody = targetDoc.getBody();
var Grafiek;
for (var i in Grafieken)
Grafiek = Grafieken[i];
var locatie = DBody.findText('%Grafiek'+i+'%').getElement().getParent().asParagraph().appendInlineImage(Grafiek);
}
}
Almost done:
function test() {
SpreadsheetApp.flush();
var Grafieken = SpreadsheetApp.getActiveSheet().getCharts();
var targetDoc = DocumentApp.openById(DOC_id);
var DBody = targetDoc.getBody();
var Grafiek;
for (var i in Grafieken)
Grafiek = Grafieken[i];
var locatie = DBody.findText('%Grafiek'+i+'%').getElement().getParent().asParagraph().appendInlineImage(Grafiek);
}
}
Related
I've started currently to use Lucene.Net to search across some txt files. I've implemented the single field search and it works awesome, but I'm stuck at the multiple fields part. It seems that the term should match all the fields to get a Hit, but I want to be able to match one or more.
For example if would have the Fields: id:10, name:exampleName, brand:exampleBrand and the term = "exampleName", then it should be a hit.
Here is what I tried:
public IEnumerable<Document> Search(string searchTerm, string[] searchFields, int limit)
{
DirectoryReader ireader = DirectoryReader.Open(_indexDirectory);
var searcher = new IndexSearcher(ireader);
var parser = new MultiFieldQueryParser(LuceneVersion.LUCENE_48, searchFields, _analyzer);
var query = parser.Parse(searchTerm);
var hits = searcher.Search(query, limit).ScoreDocs;
var documents = new List<Document>();
foreach (var hit in hits)
{
documents.Add(searcher.Doc(hit.Doc));
}
return documents;
}
but in my case I don't get a hit and I always get 0 results.
Edit:
My fault, it seems like my code is working like it should do.
I've looked extensively and tried to modify multiple sample sets of codes found on different posts in Stack Overflow as well as template documents in Google App Maker, but cannot for the life of me get an export and en email function to work.
UserRecords table:
This is the area where the data is collected and reviewed, the populated table:
These are the data fields I am working with:
This is what the exported Sheet looks like when I go through the motions and do an export through the Deployment tab:
Lastly, this is the email page that I've built based on tutorials and examples I've seen:
What I've learned so far (based on the circles I'm going round in):
Emails seem mostly straight forward, but I don't need to send a message, just an attachment with a subject, similar to using the code:
function sendEmail_(to, subject, body) {
var emailObj = {
to: to,
subject: subject,
htmlBody: body,
noReply: true
};
MailApp.sendEmail(emailObj);
}
Not sure how to change the "body" to the exported document
To straight up export and view the Sheet from a button click, the closest I've found to a solution is in Document Sample but the references in the code speak to components on the page only. I'm not sure how to modify this to use the table, and also what to change to get it as a sheet instead of a doc.
This may seem trivial to some but I'm a beginner and am struggling to wrap my head around what I'm doing wrong. I've been looking at this for nearly a week. Any help will be greatly appreciated.
In it's simplest form you can do a Google sheet export with the following server script (this is based on a model called employees):
function exportEmployeeTable() {
//if only certain roles or individuals can perform this action include proper validation here
var query = app.models.Employees.newQuery();
var results = query.run();
var fields = app.metadata.models.Employees.fields;
var data = [];
var header = [];
for (var i in fields) {
header.push(fields[i].displayName);
}
data.push(header);
for (var j in results) {
var rows = [];
for (var k in fields) {
rows.push(results[j][fields[k].name]);
}
data.push(rows);
}
if (data.length > 1) {
var ss = SpreadsheetApp.create('Employee Export');
var sheet = ss.getActiveSheet();
sheet.getRange(1,1,data.length,header.length).setValues(data);
//here you could return the URL for your spreadsheet back to your client by setting up a successhandler and failure handler
return ss.getUrl();
} else {
throw new app.ManagedError('No Data to export!');
}
}
I'm sure I'm doing something wrong... but every time I query on a calculated datasource, I get the error "cannot handle returning cyclic object."
Here's the gist:
I have a calculated model that fetches a user's google contacts and places the full name field into a table on the UI. The goal is to have a separate text box that can be used to search the full name field and then repopulate the table on the same page with the results of the search, similar to how google contacts search behavior works. The on value change event of the text box sends the textbox value to this server script:
function searchContacts (sq) {
var ds = app.models.Contacts.newQuery();
ds.filters.FullName._contains = sq;
var results = ds.run();
return results;
}
But every time I get the cyclic object error when the values are returned from that function. The error actually fires when the query run command (ds.run) is executed.
I've tried querying the datasource as well, but I've read somewhere that you can't query the datasource of a calculated model because it doesn't exist, so you have to query the model.
Any help would be much appreciated.
From your question it is not 100% clear, what you are trying to do. In case you are actually using Calculated Model, then your Server Script Query should look like this:
var sq = query.parameters.SearchQuery;
var contactsQuery = app.models.Contacts.newQuery();
contactsQuery.filters.FullName._contains = sq;
var contacts = ds.run();
var results = contacts.map(function(contact) {
var calcRecord = app.MyCalcModel.newRecord();
calcRecord.Name = contact.FullName;
return calcRecord;
});
return results;
Note, that you cannot return objects of arbitrary type from Server Script Query, only of type of this particular Calculated Model.
But from some parts of your description and error text if feels like you are trying to load records with async serever call using google.scritp.run. In this case you cannot return App Maker records(App Script doesn't allow this) and you need to map them to simple JSON objects.
I don't think I was super-clear on my original post.
I have a calculated model that is all of the user's contacts from Google Contacts (full name, email, mobile, etc...) On the UI I have a list widget that's populated with all of the Full Name fields and above the list widget a text input that's used to search the list widget. So the search text box's on input change event sends a request to query the Full Names, similar to how Google Contact's search feature works.
Screen Shot
It appears that App Maker doesn't let you query calculated models, so I have this workaround - unless someone comes up with something better:
This is the onInputChange handler for the search text box:
sq = app.pages.SelectClient.descendants.TextBox1.value;
app.datasources.SearchContacts.query.parameters.Name = sq;
app.datasources.SearchContacts.load();
This is the Server Script Code (thanks to #Pavel Shkleinik for the heads up):
var sq = query.parameters.Name;
if (sq !== null) {
return getContactsbyName(sq);
} else {
return getContacts();
}
And the server code with no query:
function getContacts() {
var results = [];
var contacts = ContactsApp.getContacts();
contacts.forEach(function(item) {
var contact = app.models.Contacts.newRecord();
contact.FullName = item.getFullName();
var emails = item.getEmails(ContactsApp.Field.WORK_EMAIL);
if (emails.length > 0) {
contact.PrimaryEmail = emails[0].getAddress();
}
contact.LastName = item.getFamilyName();
contact.FirstName = item.getGivenName();
var phones = item.getPhones(ContactsApp.Field.MOBILE_PHONE);
if (phones.length > 0) {
contact.Mobile = phones[0].getPhoneNumber();
}
var addresses = item.getAddresses(ContactsApp.Field.WORK_ADDRESS);
if (addresses.length > 0) {
contact.Address = addresses[0].getAddress();
}
results.push(contact);
results.sort();
});
return results;
}
And with the query:
function getContactsbyName(sq) {
var results = [];
var contacts = ContactsApp.getContactsByName(sq);
contacts.forEach(function(item) {
var contact = app.models.Contacts.newRecord();
contact.FullName = item.getFullName();
var emails = item.getEmails(ContactsApp.Field.WORK_EMAIL);
if (emails.length > 0) {
contact.PrimaryEmail = emails[0].getAddress();
}
contact.LastName = item.getFamilyName();
contact.FirstName = item.getGivenName();
var phones = item.getPhones(ContactsApp.Field.MOBILE_PHONE);
if (phones.length > 0) {
contact.Mobile = phones[0].getPhoneNumber();
}
var addresses = item.getAddresses(ContactsApp.Field.WORK_ADDRESS);
if (addresses.length > 0) {
contact.Address = addresses[0].getAddress();
}
results.push(contact);
results.sort();
});
return results;
}
This way, the list populates with all of the names when there's no search query present, and then re-populates with the search query results as needed.
The only issue is that the call to the Google Contacts App to populate the Calculated Model is sometimes very slow.
I'm using Rangy for highlighting text and stumbled upon a problem when calling the highlightSelection function.
highlightSelection: function(className, options) {
var converter = this.converter;
var classApplier = className ? this.classAppliers[className] : false;
options = createOptions(options, {
containerElementId: null,
selection: api.getSelection(this.doc),
exclusive: true
});
var containerElementId = options.containerElementId;
var exclusive = options.exclusive;
var selection = selection || options.selection;
var doc = selection.win.document;
var containerElement = getContainerElement(doc, containerElementId);
if (!classApplier && className !== false) {
throw new Error("No class applier found for class '" + className + "'");
}
// Store the existing selection as character ranges
var serializedSelection = converter.serializeSelection(selection, containerElement);
// Create an array of selected character ranges
var selCharRanges = [];
forEach(serializedSelection, function(rangeInfo) {
selCharRanges.push( CharacterRange.fromCharacterRange(rangeInfo.characterRange) );
});
var newHighlights = this.highlightCharacterRanges(className, selCharRanges, {
containerElementId: containerElementId,
exclusive: exclusive
});
// Restore selection
converter.restoreSelection(selection, serializedSelection, containerElement);
return newHighlights;
},
It looks like the selection object is being overridden with another call to getSelection().
What's the best way to stop it from doing that?
After doing further research, I came a cross an update by the creator of Rangy, to specifically address this issue. So,
Download the latest version of the files and make sure this is what you have in rangy-highlighter.js file under highlightSelection: function:
options = createOptions(options, {
containerElementId: null,
exclusive: true
});
var containerElementId = options.containerElementId;
var exclusive = options.exclusive;
var selection = options.selection || api.getSelection(this.doc);
var doc = selection.win.document;
var containerElement = getContainerElement(doc, containerElementId);
call the highlightSelection function like:
'highlighter.highlightSelection("highlight", {selection: sel});'
So you're setting your selection key with the value sel. 'selection' is just the name of the key expected by this function (read the github docs for more options and information) and sel should be the object your are trying to highlight and be called prior like:
'sel = rangy.getSelection();'
I am building a custom tool tip when someone highlights text, and I came across this issue. The way I solved it, was by creating a global variable range, and setting it to rangy.getSelection().getRangeAt(0). This will get you the range object for the selection, afterwards you can set the selection back to your saved value like this: rangy.getSelection().addRange(this.range)
This topic explains how to use wildcards ad the end of the searchterm using IndexedDB.
I am looking for a way to add a wildcard at the end AND at the start of the searchterm.
In SQL it would be: LIKE '%SearchTerm%'.
How can I achieve this with IndexedDB? Here is my code:
function getMaterials() {
var materialNumber = $("#input").val();
var transaction = db.transaction(["materials"]);
var objectStore = transaction.objectStore("materials");
var request = objectStore.openCursor(IDBKeyRange.bound(materialNumber, materialNumber + '\uffff'), 'prev');
$("#output").find("tr:gt(0)").remove();
request.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
var newRow = '<tr><td>'+ cursor.value.materialNumber +'</td>'+
'<td>'+ cursor.value.description +'</td>'+
'<td>'+ cursor.value.pieces +'</td>'+
'<td>'+ cursor.value.price +'</td></tr>';
$('#output').append(newRow);
cursor.continue();
}
};
};
EDIT:
I could achieve this by letting indexDB return all rows and then narrow down in JavaScript. But there must be a better approach in terms of performance.
if (cursor.value.materialNumber.indexOf(materialNumber) != -1){
//add result...
}
This was not how idb was intended to be used. If you want text searching, parse text into tokens, store the tokens, use an index on the tokens, and do lookups on the index to get a pointer to the full text.