My team is working on an Office 365 add-in for Excel, and as part of the project, we’re creating Excel documents through the GraphAPI with the end goal of having the add-in already setup for the document. We’re using the .NET OpenXml library to create the document before copying it through the GraphAPI.
We haven’t been able to find many resources for how to setup an add-in through OpenXml and have not been able to get anything working. The last thing we tried was copying the example we found here, but we couldn’t get it working. Does anyone know how to setup add-ins using the OpenXml library?
Note: the add-in is already in the Office Add-Ins store, and we have information like the AppSource ID.
Thank you!
We're actually about to publish a new sample around this scenario. The sample shows how to create an Excel document using OOXML, embed your add-in, and then upload the file to OneDrive. It also creates a Team chat that links to the file.
You can try out the sample here: Open data from your web site in a spreadsheet in Microsoft Teams
Or give us feedback on the PR: https://github.com/OfficeDev/PnP-OfficeAddins/pull/197
To answer your question about how to embed the add-in, you need to create a web extension section. I've copied the relevant code here. Note this is the same code from the Office-OOXML-EmbedAddin sample you already looked at. We reused it for the new sample. You can change the CUSTOM MODIFICATION section to provide any custom properties you want to your add-in when it opens.
// Embeds the add-in into a file of the specified type.
private void EmbedAddin(SpreadsheetDocument spreadsheet)
{
spreadsheet.DeletePart(spreadsheet.WebExTaskpanesPart);
var webExTaskpanesPart = spreadsheet.AddWebExTaskpanesPart();
CreateWebExTaskpanesPart(webExTaskpanesPart);
}
// Adds child parts and generates content of the specified part.
private void CreateWebExTaskpanesPart(WebExTaskpanesPart part)
{
WebExtensionPart webExtensionPart1 = part.AddNewPart<WebExtensionPart>("rId1");
GenerateWebExtensionPart1Content(webExtensionPart1);
GeneratePartContent(part);
}
// Generates content of webExtensionPart1.
private void GenerateWebExtensionPart1Content(WebExtensionPart webExtensionPart1)
{
// Add web extension containg Id for Script Lab add-in
We.WebExtension webExtension1 = new We.WebExtension() { Id = "{635BF0CD-42CC-4174-B8D2-6D375C9A759E}" };
webExtension1.AddNamespaceDeclaration("we", "http://schemas.microsoft.com/office/webextensions/webextension/2010/11");
// Add store information for Script Lab add-in
We.WebExtensionStoreReference webExtensionStoreReference1 = new We.WebExtensionStoreReference() { Id = "wa104380862", Version = "1.1.0.0", Store = "en-US", StoreType = "OMEX" };
We.WebExtensionReferenceList webExtensionReferenceList1 = new We.WebExtensionReferenceList();
We.WebExtensionPropertyBag webExtensionPropertyBag1 = new We.WebExtensionPropertyBag();
// Add the property that makes the taskpane visible.
We.WebExtensionProperty webExtensionProperty1 = new We.WebExtensionProperty() { Name = "Office.AutoShowTaskpaneWithDocument", Value = "true" };
webExtensionPropertyBag1.Append(webExtensionProperty1);
// CUSTOM MODIFICATION BEGIN
// Add the property that specifies the snippet to import.
string snippetToImportValue = string.Format("{{\"type\":\"gist\",\"id\":\"{0}\"}}", "{72189570-AE11-4207-9DEE-C8BDE4B83188}");
We.WebExtensionProperty webExtensionProperty2 = new We.WebExtensionProperty() { Name = "SnippetToImport", Value = snippetToImportValue };
webExtensionPropertyBag1.Append(webExtensionProperty2);
// CUSTOM MODIFICATION END
We.WebExtensionBindingList webExtensionBindingList1 = new We.WebExtensionBindingList();
We.Snapshot snapshot1 = new We.Snapshot();
snapshot1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
webExtension1.Append(webExtensionStoreReference1);
webExtension1.Append(webExtensionReferenceList1);
webExtension1.Append(webExtensionPropertyBag1);
webExtension1.Append(webExtensionBindingList1);
webExtension1.Append(snapshot1);
webExtensionPart1.WebExtension = webExtension1;
}
// Generates content of part.
private void GeneratePartContent(WebExTaskpanesPart part)
{
Wetp.Taskpanes taskpanes1 = new Wetp.Taskpanes();
taskpanes1.AddNamespaceDeclaration("wetp", "http://schemas.microsoft.com/office/webextensions/taskpanes/2010/11");
Wetp.WebExtensionTaskpane webExtensionTaskpane1 = new Wetp.WebExtensionTaskpane() { DockState = "right", Visibility = true, Width = 350D, Row = (UInt32Value)4U };
Wetp.WebExtensionPartReference webExtensionPartReference1 = new Wetp.WebExtensionPartReference() { Id = "rId1" };
webExtensionPartReference1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
webExtensionTaskpane1.Append(webExtensionPartReference1);
taskpanes1.Append(webExtensionTaskpane1);
part.Taskpanes = taskpanes1;
}
Related
Does anyone know how to create excel and ppt files through the MS Graph API? We're trying to leverage the MS Graph API to create word/excel/ppt files on a button click and while we found how to create word files, the excel and powerpoint files created are corrupted even with a success response from the api. The end point below works for the word files. We've been just working with the graph api explorer (https://developer.microsoft.com/en-us/graph/graph-explorer#) for now. Any help would be appreciated!
POST https://graph.microsoft.com/v1.0/drives/{Drive ID}/root/children/
Request Body:
{
"name": "FileTest6.docx",
"file":{
}
}
PowerPoint files
PowerPoint files could be created via DriveItem upload endpoint, for example:
PUT https://graph.microsoft.com/v1.0/me/drive/root:/sample.pptx:/content
or
POST https://graph.microsoft.com/v1.0/me/drive/root/children
{
"name": "Sample.pptx",
"file":{ }
}
Excel files
With excel files the situation is a bit different since the content of the excel file to be uploaded needs to be provided explicitly.
For ASP.NET Core application the following solution could be considered:
create empty Excel document via Open XML SDK (see CreateWorkbook example below)
upload it via DriveItem upload endpoint
C# example
using (var stream = new MemoryStream())
{
CreateWorkbook(stream);
stream.Seek(0, SeekOrigin.Begin);
var driveItem = await graphClient.Me
.Drive
.Root
.ItemWithPath("SampleWorkbook1.xlsx")
.Content
.Request()
.PutAsync<DriveItem>(stream);
}
where
public static void CreateWorkbook(Stream stream)
{
// By default, AutoSave = true, Editable = true, and Type = xlsx.
var spreadsheetDocument =
SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
var workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
// Add a WorksheetPart to the WorkbookPart.
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet"};
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
I am importing data and documents from third party application into Acumatica.
After importing, I am creating Vendor dynamically using below code along with attachments.
VendorMaint graph = PXGraph.CreateInstance<VendorMaint>();
VendorR row1 = null;
row1 = new VendorR();
row1.AcctName = VendorName;
row1.NoteID = noteid; // Existing - GUID created while importing
graph.BAccount.Update(row1);
If attachment already exists then it should update instead of duplicating.
In this case if Vendor already exists with files attached, then my code overrides these attachments and remove all previous files attached to that existing vendor.
I want to add the attachment instead of override the existing attachment. Any suggestion?
Try to use insert method of view:
VendorMaint graph = PXGraph.CreateInstance<VendorMaint>();
var row1 = new VendorR();
row1 = graph.BAccount.Insert(row1);
if (row1 == null) // already inserted or wasn't able to insert
{
//some logic with newly created vendor
}
else
{
//some logic with existed
}
row1.AcctName = "vendor name";
row1.NoteID = noteid; // Existing - GUID created while importing
graph.BAccount.Update(row1);
I have found the solution for the issue. Below code helps to create a new attachment and does not override any existing attachments for an existing Vendor.
// Getting the FileID of the attached file from DACClass
UploadFile uf = PXSelectJoin<UploadFile,
InnerJoin<NoteDoc, On<NoteDoc.fileID, Equal<UploadFile.fileID>>,
InnerJoin<DACClass, On<DACClass.noteID, Equal<NoteDoc.noteID>>>>,
Where<DACClass.noteID, Equal<Required<DACClass.noteID>>>>.Select(this, noteid);
if (uf != null)
{
PXNoteAttribute.SetFileNotes(graph.BAccount.Cache, graph.BAccount.Current, uf.FileID.Value);
NoteDoc doc = new NoteDoc();
doc.NoteID = uf.FileID.Value;
doc.FileID = new Guid();
graph.BAccount.Cache.Insert(doc);
}
I have following code from http://ktskumar.wordpress.com/2009/03/03/upload-document-from-local-machine-to-sharepoint-library/ to upload a document to a sharepoint library using web services. I have added https://mysite.sharepoint.com/_vti_bin/Copy.asmx (this site is on sharepoint Online) as my service reference.
//Copy WebService Settings
string webUrl = "https://mySite.sharepoint.com";
WSCopy.Copy copyService = new WSCopy.Copy();
copyService.Url = webUrl + "/_vti_bin/copy.asmx";
copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;
//Source and Destination Document URLs
string sourceUrl = "http://localhost/Shared Documents/Sample.doc";
string destinationUrl = "E:\\DocumentsSample.doc";
//Variables for Reading metadata’s of a document
WSCopy.FieldInformation fieldInfo = new WSCopy.FieldInformation();
WSCopy.FieldInformation[] fieldInfoArray = { fieldInfo };
WSCopy.CopyResult cResult1 = new WSCopy.CopyResult();
WSCopy.CopyResult cResult2 = new WSCopy.CopyResult();
WSCopy.CopyResult[] cResultArray = { cResult1, cResult2 };
//Receive a Document Contents into Byte array (filecontents)
byte[] fileContents = new Byte[4096];
uint copyresult = copyService.GetItem(sourceUrl, out fieldInfoArray, out fileContents);
if (copyresult == 0)
{
Console.WriteLine("Document downloaded Successfully, and now it's getting saved in location " + destinationUrl);
//Create a new file and write contents to that document
FileStream fStream = new FileStream(destinationUrl, FileMode.Create, FileAccess.ReadWrite);
fStream.Write(fileContents, 0, fileContents.Length);
fStream.Close();
}
else
{
Console.WriteLine("Document Downloading gets failed...");
}
Console.Write("Press any key to exit...");
Console.Read();
here WSCopy is the service reference and 'WSCopy.Copy' copy class is not found on my project. How can i resolve this or is there another way to achive my goal.
Refer to this post
http://www.ktskumar.com/blog/2009/03/upload-document-from-local-machine-to-sharepoint-library/
You have to add the web service url in Web Reference, instead of Service Reference.
On Visual Studio Project, Right click the References, and select the Add Service Reference.
On Add Service Reference popup, click the Advanced button on bottom of the box,
Now the Service Reference Settings popup will open, there we have to click the “Add Web Reference” botton. Then give the Web Service url and click the “Add Reference” button to include webservice url to the project.
I am using Open XML SDK for creating excel files.
I want to protect them with a password.
Do you know anyway to protect excel file with a password by using Open XML SDK?
I know "com" object way to protect them however, it is not suitable for my application. I need to protect file by using Open XML SDK or another way.
Creating an excel password for protecting workbook or worksheet is possible by open xml.
Following code samples are suggestions of Vincent (http://spreadsheetlight.com/about/) (https://stackoverflow.com/users/12984/vincent-tan) (again I thank him a lot :)
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docname,true))
{
foreach (var worksheet in spreadSheet.WorkbookPart.WorksheetParts)
{
worksheet.Worksheet.Append(new SheetProtection(){ Password = “CC”});
// add this in case it still doesn’t work. This makes sure the data is saved.
//worksheet.Worksheet.Save();
}
}
If you have a chart or something then
Following code samples are suggestions of Vincent (http://spreadsheetlight.com/about/) (https://stackoverflow.com/users/12984/vincent-tan) (again I thank him a lot :)
bool bFound;
OpenXmlElement oxe;
SheetProtection prot;
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open("OtoPark.xlsx", true))
{
foreach (var worksheet in spreadSheet.WorkbookPart.WorksheetParts)
{
prot = new SheetProtection();
prot.Password = "CC";
// these are the "default" Excel settings when you do a normal protect
prot.Sheet = true;
prot.Objects = true;
prot.Scenarios = true;
// Open up Excel and do a password protect yourself and use the
// Productivity Tool to see the property values of the resulting Excel file.
// Consider not using the Password property and use:
//prot.AlgorithmName = "SHA-512";
//prot.HashValue = "somehashvaluebythealgorithm";
//prot.SaltValue = "somesalt";
//prot.SpinCount = 100000;
bFound = false;
oxe = worksheet.Worksheet.FirstChild;
foreach (var child in worksheet.Worksheet.ChildElements)
{
// start with SheetData because it's a required child element
if (child is SheetData || child is SheetCalculationProperties)
{
oxe = child;
bFound = true;
}
}
if (bFound)
{
worksheet.Worksheet.InsertAfter(prot, oxe);
}
else
{
worksheet.Worksheet.PrependChild(prot);
}
worksheet.Worksheet.Save();
}
}
These methods makes a protection that any user cant change the data accidentally. However, if you do not want any user that don't know password to see the data then you can use following library:
http://dotnetzip.codeplex.com/
You have a password protected zipped file that contains your excel.xlsx file by using the dotnetzip library.
An example:
public void RNCreateZipFile(string ExcelDocName,string PassWord, string ZipDocName)
{
// create a zip
using (var zip = new ZipFile())
{
zip.Password = PassWord;
zip.AddFile(ExcelDocName, "");
zip.Save(ZipDocName);
}
}
As #Birol mentioned that it will only protect (or rather lock) WB or WS but user can still open file in read only mode. Using dotnetzip package, it will password protect the files inside zip but it will allow the user to see the file second time without asking for password as it is the default windows behavior. You can use free Spire.XLS which will prompt you to enter password to open it any time. It has some limitations though. You can refer - https://www.nuget.org/packages/FreeSpire.XLS/
I have a form library in my share point site. Programmatically I need to fill some fields. Can I do that? If any one know please provide me some sample code. First I need to retrieve the infopath document and then I need to fill the fields.
What axel_c posted is pretty dang close. Here's some cleaned up and verified working code...
public static void ChangeFields()
{
//Open SharePoint site
using (SPSite site = new SPSite("http://<SharePoint_Site_URL>"))
{
using (SPWeb web = site.OpenWeb())
{
//Get handle for forms library
SPList formsLib = web.Lists["FormsLib"];
if (formsLib != null)
{
foreach (SPListItem item in formsLib.Items)
{
XmlDocument xml = new XmlDocument();
//Open XML file and load it into XML document
using (Stream s = item.File.OpenBinaryStream())
{
xml.Load(s);
}
//Do your stuff with xml here. This is just an example of setting a boolean field to false.
XmlNodeList nodes = xml.GetElementsByTagName("my:SomeBooleanField");
foreach (XmlNode node in nodes)
{
node.InnerText = "0";
}
//Get binary data for new XML
byte[] xmlData = System.Text.Encoding.UTF8.GetBytes(xml.OuterXml);
using (MemoryStream ms = new MemoryStream(xmlData))
{
//Write data to SharePoint XML file
item.File.SaveBinary(ms);
}
}
}
}
}
}
The Infopath document is just a regular XML file, the structure of which matches the data sources you defined in the Infopath form.
You just need to access the file via the SharePoint object model, modify it using standard methods (XmlDocument API) and then write it back to the SharePoint list. You must be careful to preserve the structure and insert valid data or you won't be able to open the form using Infopath.
You should really check out a book on SharePoint if you plan to do any serious development. Infopath is also a minefield.
Object model usage examples: here, here and here. The ridiculously incomplete MSDN reference documentation is here.
EDIT: here is some example code. I haven't done SharePoint for a while so I'm not sure this is 100% correct, but it should give you enough to get started:
// Open SharePoint site
using (SPSite site = new SPSite("http://<SharePoint_Site_URL>"))
{
using (SPWeb web = site.OpenWeb())
{
// Get handle for forms library
SPList formsLib = web.Lists["FormsLib"];
if (formsLib != null)
{
SPListItem itm = formsLib.Items["myform.xml"];
// Open xml and load it into XML document
using (Stream s = itm.File.OpenBinary ())
{
MemoryStream ms;
byte[] xmlData;
XmlDocument xml = new XmlDocument ();
xml.Load (s);
s.Close ();
// Do your stuff with xml here ...
// Get binary data for new XML
xmlData = System.Text.Encoding.UTF8.GetBytes (xml.DocumentElement.OuterXml);
ms = new MemoryStream (xmlData);
// Write data to sharepoint item
itm.File.SaveBinary (ms);
ms.Close ();
itm.Update ();
}
}
web.Close();
}
site.Close();
}
It depends a bit on your available tool set, skills and exact requirements.
There are 2 main ways of pre populating data inside an InfoPath form.
Export the relevant fields as part of the form's publishing process. The fields will then become columns on the Document / Forms library from where you can manipulate them either manually, via a Workflow or wherever your custom code is located.
Directly manipulate the form using code similar to what was provided by Axel_c previously. The big question here is: what will trigger this code? An event receiver on the Document Library, a SharePoint Designer Workflow, a Visual Studio workflow etc?
If you are trying to do this from a SharePoint Designer workflow then have a look at the Workflow Power Pack for SharePoint. It allows C# and VB code to be embedded directly into the workflow without the need for complex Visual Studio development. An example of how to query InfoPath data from a workflow can be found here. If you have some development skills you should be able to amend it to suit your needs.
I also recommend the site www.infopathdev.com, they have excellent and active forums. You will almost certainly find an answer to your question there.
Thanks for the sample code, #axel_c and #Jeff Burt
Below is just the same code from Jeff Burt modified for a file in Document set which I needed. If you don't already have the Document Set reference, you can check out this site on how to grab one:
http://howtosharepoint.blogspot.com/2010/12/programmatically-create-document-set.html
Also, the codes will open the .xml version of the infopath form and not the .xsn template version which you might run into.
Thanks again everyone...
private void ChangeFields(DocumentSet docSet)
{
string extension = "";
SPFolder documentsetFolder = docSet.Folder;
foreach (SPFile file in documentsetFolder.Files)
{
extension = Path.GetExtension(file.Name);
if (extension != ".xml") //check if it's a valid xml file
return;
XmlDocument xml = new XmlDocument();
//Open XML file and load it into XML document, needs to be .xml file not .xsn
using (Stream s = file.OpenBinaryStream())
{
xml.Load(s);
}
//Do your stuff with xml here. This is just an example of setting a boolean field to false.
XmlNodeList nodes = xml.GetElementsByTagName("my:fieldtagname");
foreach (XmlNode node in nodes)
{
node.InnerText = "xyz";
}
//Get binary data for new XML
byte[] xmlData = System.Text.Encoding.UTF8.GetBytes(xml.OuterXml);
using (MemoryStream ms = new MemoryStream(xmlData))
{
//Write data to SharePoint XML file
file.SaveBinary(ms);
}
}
}
I had this issue and resolved it with help from Jeff Burt / Axel_c's posts.
I was trying to use the XMLDocument.Save([stream]) and SPItem.File.SaveBinary([stream]) methods to write an updated InfoPath XML file back to a SharePoint library. It appears that XMLDocument.Save([stream]) writes the file back to SharePoint with the wrong encoding, regardless of what it says in the XML declaration.
When trying to open the updated InfoPath form I kept getting the error "a calculation in the form has not been completed..."
I've written these two functions to get and update and InfoPath form. Just manipulate the XML returned from ReadSPFiletoXMLdocument() in the usual way and send it back to your server using WriteXMLtoSPFile().
private System.Xml.XmlDocument ReadSPFiletoXMLdocument(SPListItem item)
{
//get SharePoint file XML
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
try
{
using (System.IO.Stream xmlStream = item.File.OpenBinaryStream())
{
xDoc.Load(xmlStream);
}
}
catch (Exception ex)
{
//put your own error handling here
}
return xDoc;
}
private void WriteXMLtoSPFile(SPListItem item, XmlDocument xDoc)
{
byte[] xmlData = System.Text.Encoding.UTF8.GetBytes(xDoc.OuterXml);
try
{
using (System.IO.MemoryStream outStream = new System.IO.MemoryStream(xmlData))
{
item.File.SaveBinary(outStream);
}
}
catch (Exception ex)
{
//put your own error handling here
}
}