I'm having problem binding data to content control using ooxml and office.js - ms-word

I'm developing a word addin that pulls xml data from our servers and binds it to a rich text content control. The user should only be able to format the data within the content control but can't edit or delete the data.
This is the code i've been able to come up with but it's not working..
var ooxmlPackage = new DOMParser().parseFromString(
'<pkg:package xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage"></pkg:package>',
"text/xml"
);
var ooxmlPart = ooxmlPackage.createElement("pkg:part");
ooxmlPart.setAttribute("pkg:name", "/_rels/.rels");
ooxmlPart.setAttribute("pkg:contentType", "application/vnd.openxmlformats-package.relationships+xml");
ooxmlPart.setAttribute("pkg:padding", "512");
var ooxmlxmlData = ooxmlPackage.createElement("pkg:xmlData");
var ooxmlRelationships = ooxmlPackage.createElement("Relationships");
ooxmlRelationships.setAttribute("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships");
var ooxmlRelationship = ooxmlPackage.createElement("Relationship");
ooxmlRelationship.setAttribute("Id", "rId1"); //TODO: generate unique ID
ooxmlRelationship.setAttribute(
"Type",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
);
ooxmlRelationship.setAttribute("Target", "word/document.xml");
ooxmlRelationships.appendChild(ooxmlRelationship);
ooxmlxmlData.appendChild(ooxmlRelationships);
ooxmlPart.appendChild(ooxmlxmlData);
var ooxmlDocPart = ooxmlPackage.createElement("pkg:part");
ooxmlDocPart.setAttribute("pkg:name", "/word/document.xml");
ooxmlDocPart.setAttribute(
"pkg:contentType",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
);
var ooxmlDocPartxmlData = ooxmlPackage.createElement("pkg:xmlData");
var ooxmlDocument = ooxmlPackage.createElement("w:document");
ooxmlDocument.setAttribute("xmlns:w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
ooxmlDocument.setAttribute("xmlns:w15", "http://schemas.microsoft.com/office/word/2012/wordml");
var ooxmlDocumentBody = ooxmlPackage.createElement("w:body");
var ooxmlDocumentParagraph1 = ooxmlPackage.createElement("w:p");
var ooxmlContentControl = ooxmlPackage.createElement("w:sdt");
var sdtPr = ooxmlPackage.createElement("w:sdtPr");
//var lk = ooxmlPackage.createElement("w:lock");
//lk.setAttribute("w:val", "sdtContentLocked");
//sdtPr.appendChild(lk);
var alias = ooxmlPackage.createElement("w:alias");
alias.setAttribute("w:val", "MyControl");
sdtPr.appendChild(alias);
var id1 = ooxmlPackage.createElement("w:id");
id1.setAttribute("w:val", "1382295294");
sdtPr.appendChild(id1);
//var appr = ooxmlPackage.createElement("w15:appearance");
//appr.setAttribute("w15:val", "hidden");
//sdtPr.appendChild(appr);
sdtPr.appendChild(ooxmlPackage.createElement("w:showingPlcHdr"));
//var plchdlr = ooxmlPackage.createElement("w:placeholder");
//var docPrt = ooxmlPackage.createElement("docPart");
//docPrt.setAttribute("w:val", "defaultPlaceHolder_-1854013440");
//plchdlr.appendChild(docPrt);
//sdtPr.appendChild(plchdlr);
var bindingNode = ooxmlPackage.createElement("w15:dataBinding");
//bindingNode.setAttribute("w:prefixMappings","xmlns:ns0='custom'");
bindingNode.setAttribute("w:xpath","/Root[1]/Node[1]");
bindingNode.setAttribute("w:storeItemID", "{C2F77B86-6131-4922-803B-54FACB654C16}");
sdtPr.appendChild(bindingNode);
ooxmlContentControl.appendChild(sdtPr);
var sdtContent = ooxmlPackage.createElement("w:sdtContent");
var parag = ooxmlPackage.createElement("w:p");
var r = ooxmlPackage.createElement("w:r")
var t = ooxmlPackage.createElement("w:t")
//t.innerHTML= '[This is a test]';
r.appendChild(t);
parag.appendChild(r);
sdtContent.appendChild(parag);
ooxmlContentControl.appendChild(sdtContent);
ooxmlDocumentBody.appendChild(ooxmlDocumentParagraph1);
ooxmlDocumentBody.appendChild(ooxmlContentControl);
ooxmlDocument.appendChild(ooxmlDocumentBody);
ooxmlDocPartxmlData.appendChild(ooxmlDocument);
ooxmlDocPart.appendChild(ooxmlDocPartxmlData);
ooxmlPackage.documentElement.appendChild(ooxmlPart);
ooxmlPackage.documentElement.appendChild(ooxmlDocPart);
var serializer = new XMLSerializer();
var ooxmlPackageString = serializer.serializeToString(ooxmlPackage);
console.log(ooxmlPackageString);
Office.context.document.setSelectedDataAsync(ooxmlPackageString, { coercionType: "ooxml" });
Office.context.document.customXmlParts.getByIdAsync(
'<Root xmlns=""> <Node>VALUE1</Node></root>',
function (result) { });
It just inserts an empty content control when it runs, it doesn't map the xml node data as expected.

Related

How to send emails based on data filled in a form?

function ifstatement() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Product Form");
const ws2 = ss.getSheetByName("Email details");
var Avals = ws.getRange("c1:c").getValues();
var lr = Avals.filter(String).length;
Logger.log(lr);
var recipient = ws.getRange(lr,2).getValue();
var sub = ws.getRange(lr,4).getValue();
var mailTemp = ws.getRange(lr,5).getValue();
var impfield1 = ws.getRange(lr,6).getValue();
var impfield2 = ws.getRange(lr,8).getValue();
var impfield3 = ws.getRange(lr,10).getValue();
var fieldvalue1 = ws.getRange(lr,7).getValue();
var fieldvalue2 = ws.getRange(lr,9).getValue();
var fieldvalue3 = ws.getRange(lr,11).getValue();
var heading = ws.getRange(lr,12).getValue();
var subheading = ws.getRange(lr,13).getValue();
var body = ws.getRange(lr,14).getValue();
var footer = ws.getRange(lr,15).getValue();
var attach = ws.getRange(lr,17).getValue();
var tomail = ws.getRange(lr,16).getValue();
var file1 = attach.split(",").map(url => DriveApp.getFileById(url.trim().split("=")[1]).getBlob());
var AvalsWealth = ws2.getRange("b1:b").getValues();
var AvalsInsurance = ws2.getRange("c1:c").getValues();
var AvalsTeam = ws2.getRange("e1:e").getValues();
var lrWealth = AvalsWealth.filter(String).length;
var lrInsurance = AvalsInsurance.filter(String).length;
var lrTeam = AvalsTeam.filter(String).length;
Logger.log(mailTemp);
Logger.log(heading);
if(tomail=="Wealth RMs"){
var bccmail = ws2.getRange(2,2,lrWealth).getValues().toString();
} else if(tomail=="Self"){
var bccmail = recipient;
} else if(tomail=="Insurance RMs"){
var bccmail = ws2.getRange(2,3,lrInsurance).getValues().toString();
} else if(tomail=="All India"){
var bccmail = ws2.getRange(2,4,lrTeam).getValues().toString();
}
Logger.log(bccmail)
if(mailTemp=="HTML1"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML1");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) } else if(mailTemp=="HTML2"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML2");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) } else if(mailTemp=="HTML3"){
const htmlTemplate = HtmlService.createTemplateFromFile("AUM Annual awards");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail}
) } else if(mailTemp=="HTML4"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML4");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('mayank.agarwal#aumcap.com',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) }
}
I have this small setup where I have a Google Sheet, Google Appscript and Google form.
The user needs to input data in a Google Form - and once the sheet (linked with Form response) receives the updated row - a script is triggered which takes the data from the row and feeds it into the sheet and sends mail to the selected set of users.
Now the problem I am facing is that I need to send this mail to approx 100-150 people, however Googel appscript does not allow me to send mail to more than 30 participants at a time.
I understand that I need an Email service for this, however, I am unable to find any good solution wherein I can store my templates and the user just fills up data fields and shoots the mail.
Maybe because I am very new to this tech field so thats why.
Can anyone please guide me as to what is the setup I need to use for my purpose?
Thanks!
The first thing you need to do is to keep the BCC list as an array until it's necessary. This will allow us to make chunks out of it. This means removing the .toString() at the end of assigning bccmail.
Then, we need a custom function to send the email in batches of emails. I'm calling that function sendMassEmail.
function sendMassEmail(bccList, subject, plainBody, htmlBody, attachments) {
for (let bcc of chunks(bccList, 30)) {
GmailApp.sendEmail(
'',
subject,
plainBody,
{
htmlBody,
bcc: bcc.join(','),
attachments,
},
)
}
}
Chunks is a function that does exactly that, gets the elements of an array in chunks. My favorite implementation for this case is by using a generator.
I've kept the plain text body as it's important to generate it if you are sending it, as it is shown in most clients on the Inbox. Also, some of them can only read this ones (think smart watch).
The last argument (attachments) is optional.
Here is an example on how you would use it:
sendMassEmail(
bccmail,
sub.toString(),
'', // Should probably change it
htmlforemail,
file1,
)
Note that it's better to use toString() than concatenating into an empty string.
References
GmailApp.sendEmail(recipient, subject, body, options) (Apps Script reference)
for..of (MDN JavaScript reference)
Functions (MDN JavaScript guide)
Split array into chunks (StackOverflow question)

Unable to add inline image to email in google apps script

I'm new to Google Apps script and am trying to add an image inline to an automated response email.
The auto reply works perfectly, the main text of the email formats well in plain text and html.
the problem i'm facing is that the image does not appear.
my code:
// This constant is written in column Y for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Data'))
var startRow = 2; // First row of data to process
// Fetch the range
var dataRange = sheet.getRange("L2:L1000")
var dataRange2 = sheet.getRange("K2:K1000")
var dataRange3 = sheet.getRange("O2:O1000")
var dataRange4 = sheet.getRange("Y2:Y1000")
var dataRange5 = sheet.getRange("B2:B1000")
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var data2 = dataRange2.getValues();
var data3 = dataRange3.getValues();
var data4 = dataRange4.getValues();
var data5 = dataRange5.getValues();
for (var i = 0; i < data.length; ++i) {
var yesno = data2[i]
if(yesno == "Yes"){
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp
.fetch(TFlogoUrl)
.getBlob()
.setName("TFlogoBlob");
var emailAddress = data[i];
var ShipID = data3[i];
var cmdrID = data5[i];
var TFmsg = "Hi " + cmdrID + ",/n /nThank you for signing up to The Fatherhoods Lost Souls Expedition./n /nYour unique Ship ID is: " + ShipID + "/n /nWe look forward to seeing you on the expedition CMDR!/n /nFly Safe,/nThe Lost Souls Expedition team.";
var htmlTFmsg = "Hi " + cmdrID + ",<br> <br>Thank you for signing up to The Fatherhoods Lost Souls Expedition.<br> <br>Your unique Ship ID is: " + ShipID + "<br> <br>We look forward to seeing you on the expedition CMDR!<br> <br>Fly Safe,<br>The Lost Souls Expedition team.<br><img src='cid:TFlogo'>";
emailSent = data4[i]; // email sent (column Y)
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Lost Souls Expedition Sign up confirmation";
MailApp.sendEmail(emailAddress,subject,TFmsg,{
htmlBody: htmlTFmsg,
inlineImage:
{
TFlogo:TFlogoBlob
}
});
sheet.getRange("Y" + (startRow + i)).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
}
How about this modification?
Modification points:
You cannot retrieve the file blob from this URL var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. If you want to retrieve the file blob from URL, please use var TFlogoUrl = "http://drive.google.com/uc?export=view&id=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. 1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287 is the file ID.
As an another method, from the file ID, it is found that the values of getSharingAccess() and getSharingPermission() are ANYONE_WITH_LINK and VIEW, respectively. So you can also retrieve the blob using var TFlogoBlob = DriveApp.getFileById("1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287").getBlob().setName("TFlogoBlob");. I recommend this.
When you want to use the inline image to email, please modify from inlineImage to inlineImages.
The script which reflected above points is as follows.
Modified script:
Please modify your script as follows.
From:
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp.fetch(TFlogoUrl).getBlob().setName("TFlogoBlob");
To:
var id = "1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = DriveApp.getFileById(id).getBlob().setName("TFlogoBlob");
And
From:
inlineImage: {TFlogo:TFlogoBlob}
To:
inlineImages: {TFlogo:TFlogoBlob}
References:
sendEmail(recipient, subject, body, options)
If I misunderstand your question, please tell me. I would like to modify it.

Corrupt records from OpenXML Spreadsheet creation

I'm trying to generate a simple XLSX file using OpenXML but I'm getting an error when I open my file and the only info in the repairedRecord part of the log file is this:
Repaired Records: Cell information from /xl/worksheets/sheet1.xml part
The strange thing is that all the cells I'm trying to write do have the value I expect them to have. I'm just trying to write a single header row right now, where the headers is just an IEnumerable<string>:
using (var doc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook)) {
var workbookPart = doc.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet {
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet 1"
};
sheets.Append(sheet);
workbookPart.Workbook.Save();
var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
var row = new Row { RowIndex = 1 };
var column = 1;
foreach (var header in headers)
row.AppendChild(new Cell {
CellReference = GetColumnLetter(column++) + "1",
DataType = CellValues.SharedString,
CellValue = new CellValue(header)
});
sheetData.Append(row);
workbookPart.Workbook.Save();
}
If you're inserting a string value, you should be using CellValues.InlineString
foreach (var header in headers)
row.AppendChild(new Cell (new InlineString(new Text(header))) {
CellReference = GetColumnLetter(column++) + "1",
DataType = CellValues.InlineString
});

Filtering with more than one parameter in sapui5

I am working on an odata fiori app & I want to filter my list depending on two parameters and not just one : "Mpobj" & "Atinn", so i tried this code :
_onObjectMatched: function(oEvent) {
var sObjectPath = oEvent.getParameter("arguments").infosId;
var sObjectPath1 = oEvent.getParameter("arguments").objectI;
var oView = this.getView();
oView.bindElement(sObjectPath, sObjectPath1);
var frag = this.getView().byId("tableid1");
var oFilter = new sap.ui.model.Filter("Mpobj", sap.ui.model.FilterOperator.Contains, sObjectPath);
var oFilter1 = new sap.ui.model.Filter("Atinn", sap.ui.model.FilterOperator.Contains, sObjectPath1);
frag.bindElement("Infos" + "/mesureSet").getBinding("items").filter([oFilter], [oFilter1]);
},
But when i debugg, it appears that he's reading the first parameter "Mpobj" but doesn't recognize the second one "Atinn".
Any suggestions ?
You should use just one array. Try the following
var aFilters=[];
var oFilter = new sap.ui.model.Filter("Mpobj", sap.ui.model.FilterOperator.Contains, sObjectPath);
aFilters.push(oFilter);
var oFilter1 = new sap.ui.model.Filter("Atinn", sap.ui.model.FilterOperator.Contains, sObjectPath1);
aFilters.push(oFilter1);
frag.bindElement("Infos" + "/mesureSet").getBinding("items").filter(aFilters);

Sending email from spreadsheet onOpen

I have a script that performs a CRM system on my company and I am using Fusion table as a database. Every time i enter a new record, this record is saved on this fusion table. When the save action is performed, I use the follow code to make a copy of the data, that is passed to the database, in on spreadsheet so I have a backup of the data:
function AtualizarSpreadsheet(e)
{
var app = UiApp.getActiveApplication();
var planilha = SpreadsheetApp.openById(SPREADSHEET_ID);
var sheet = planilha.getActiveSheet();
var enviado = "NÃO";
var id = e.parameter.id;
var nomeDoReclamante = e.parameter.nomeDoReclamante;
var telefone = e.parameter.telefone;
var ddd = e.parameter.ddd;
var prefixo = e.parameter.prefixo;
var sufixo = e.parameter.sufixo;
var email = e.parameter.email;
var regiao = e.parameter.regio;
var categoria = e.parameter.categoria;
var produto = e.parameter.produto;
var subcategoria = e.parameter.subcategoria;
var versaoDeSoftware = e.parameter.versoDeSoftware;
var dataDeInicio = e.parameter.dataDeInicio;
var dia = e.parameter.dia;
var mes = e.parameter.ms;
var ano = e.parameter.ano;
var tituloDoProblema = e.parameter.ttuloDoProblema;
var descricao = e.parameter.descrio;
var status = e.parameter.status;
var prioridade = e.parameter.prioridade;
var informarEngenharia = e.parameter.informarEngenharia;
var dataDeRegistro = e.parameter.dataDeRegistro;
var horaDeRegistro = e.parameter.horaDeRegistro;
var historico = e.parameter.histrico;
var ordem = e.parameter.ordem;
sheet.s
sheet.appendRow([enviado,
id,
nomeDoReclamante,
telefone,
ddd,
prefixo,
sufixo,
email,
regiao,
categoria,
produto,
subcategoria,
versaoDeSoftware,
dataDeInicio,
dia,
mes,
ano,
tituloDoProblema,
descricao,
status,
prioridade,
informarEngenharia,
dataDeRegistro,
horaDeRegistro,
historico,
ordem]);
return app;
}
On the spreadsheet I perform a function onOpen() to send one email everytime the spreadsheet is oppened.
However when my fusion table script performs the command: SpreadsheetApp.openById(SPREADSHEET_ID); the onOpen() function is not being triggered. Even if I oppen the spreadsheet I cant have that function runned.
The onOpen() function is detailed bellow:
function onOpen()
{
MailApp.sendEmail("EMAIL", "SUBJECT", "BODY");
}
What am I doing wrong?
You are attempting to call a service (MailApp) that is not supported in a simple trigger. You would need to call your onOpen() function something different, and attach an installable "on open" trigger to it instead.
https://developers.google.com/apps-script/understanding_triggers