So I've created a C# library that manipulates and edits Word Documents. This of course references the OpenXML SDK. Where I use the library however I do not wan't to have to reference the .dll as well.
One method that I might use from another project has a WordprocessingDocument
parameter and has this profile:
public bool FillTemplate(ref WordprocessingDocument document, XElement data)
{
//EDIT the document and return True if succesful.
}
problem here is of course that I would have to create a WordprocessingDocument
inside the other project instead of just passing a stream.
Ok I guess the simplest solution would be a different profile on the method:
public bool FillTemplate(Stream document, XElement data)
{
WordprocessingDocument doc = WordprocessingDocument.Open(document, true);
return FillTemplate(doc, data);
}
But I got what I thought would be a brilliant idea just to create a extension method for Stream:
public static WordprocessingDocument ConvertToWordDocument(this Stream stream, bool isEditable)
{
return WordprocessingDocument.Open(stream, isEditable);
}
and use it like this:
FileSt开发者_运维知识库ream fStream = new FileStream(@"C:\Users\Me\Desktop\SomeDoc.docx", FileMode.Open);
var doc = fStream.ConvertToWordDocument(true);
filler.FillTemplate(ref doc, getXmlDataFor(42));
fStream.Flush();
fStream.Close();
However this doesn't work for some reason (Doc changes but it doesn't seem to get returned to the stream) and I got a little skeptical about the whole idea of how I'm using Streams and the WordprocessingDocument
package/wrapper thingy.
What would be a optimal solution so I'm not going into a whole lot of trouble? How actually does the WordprocessingDocument
class work in relation to passing it around as a parameter and such? Why didn't the stream change the originally opened document?
System.IO.Packaging.Package
seems to be the way to go when handling opc packages. Following lines of code looks fine to me. Package.Open have a number of constructors that you can use with path strings, streams etc...
System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(@"C:\Users\Me\Desktop\SomeDoc.docx");
DocumentFormat.OpenXml.Packaging.WordprocessingDocument document = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(package, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
// edit document
package.Flush();
package.Close();
精彩评论