Reputation: 127
Is it possible to use the Open XML sdk to manipulate parts of document which is currently open in the Office app (word/ppt). I know the easiest thing is to use VSTO, but its slow and would involve clipboard use to insert elements, the OXML sdk is direct and simpler.
If somebody could post some code sample that would be great.
Thanks in advance
Rakesh
Upvotes: 8
Views: 3264
Reputation: 1303
I was able to do this using an Excel Document using ClosedXML as such (after saving the file to disk as the path excelFileName):
byte[] byteArray = null;
using (var fs = new FileStream(excelFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
int numBytesToRead = Convert.ToInt32(fs.Length);
byteArray = new byte[numBytesToRead];
fs.Read(byteArray, 0, numBytesToRead);
}
using (MemoryStream mem = new MemoryStream()) {
mem.Write(byteArray, 0, byteArray.Length);
XLWorkbook wb = new XLWorkbook(mem);
...
}
In my case I am only reading the document and will not be saving it, but you could write the modified stream to another file if necessary.
Upvotes: 0
Reputation: 1945
Yes it is possible to modify an open VSTO document, using the OpenXML sdk 2, then update your open document using the changed xml.
http://msdn.microsoft.com/en-us/library/ff191178.aspx
http://code.msdn.microsoft.com/Improve-Automation-415bff13
Basically you get the xml from a range, treat it as a stream, package it up, use the sdk on the package, then insert the modified xml back by reversing the process.
The wisdom out there is that this common sense usage of the sdk is not possible. However, this is just wrong.
Upvotes: 5
Reputation: 127
Apparently you cannot do this without Sharepoint.
As per Zeyad Jarabi/..
...you need a platform that understands how to take a shared lock (like SharePoint or SkyDrive). Without this concept then the application and the SDK can only take read or write locks, which prevents these two pieces of technology from accessing the same file.
Upvotes: -1
Reputation: 15139
Something like below:-
//include the namespace
using DocumentFormat.OpenXml.WordProcessing
//Open and manipulate temp.docx
using (WordprocessingDocument myDoc = WordprocessingDocument.Open("temp.docx", true))
{
//Access main part of document
MainDocumentPart mainPart = myDoc.MainDocumentPart;
//Add new comments part to document
mainPart.AddNewPart<WordprocessingCommentsPart>();
//Delete Styles part within document
mainPart.DeletePart(mainPart.StyleDefinitionsPart);
//Iterate through all custom xml parts within document
foreach (CustomXmlPart customXmlPart in mainPart.CustomXmlParts) {
//DO SOMETHING
}
}
Also, you could use LINQ to avoid foreach loops.
Upvotes: 0