Mit dieser Funktion kann man in einem Word-Dokument nach Bookmarks bzw. Textmarken suchen und diese dann auch ersetzen. Für die Funktion wird die Library „OpenXML“ benötigt. An die statische Funktion wird ein SPFile übergeben.
enum ModifyDocumentResults
{
Success,
InvalidFileFormat
}
static ModifyDocumentResults ModifyDocument(SPFile file)
{
byte[] byteArray = file.OpenBinary();
using (MemoryStream mem = new MemoryStream())
{
mem.Write(byteArray, 0, (int)byteArray.Length);
try
{
using (WordprocessingDocument wordDoc =
WordprocessingDocument.Open(mem, true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
Body body = mainPart.Document.GetFirstChild();
var paras = body.Elements();
//Iterate through the paragraphs to find the bookmarks inside
foreach (var para in paras)
{
var bookMarkStarts = para.Elements();
var bookMarkEnds = para.Elements();
foreach (BookmarkStart bookMarkStart in bookMarkStarts)
{
if (bookMarkStart.Name == "Name")
{
//Get the id of the bookmark start to find the bookmark end
var id = bookMarkStart.Id.Value;
var bookmarkEnd = bookMarkEnds.Where(i => i.Id.Value == id).First();
var runElement = new Run(new Text("Einhorn"));
para.InsertAfter(runElement, bookmarkEnd);
}
}
}
mainPart.Document.Save();
}
// write it back to the document library
// change linkFilename if you want to write to a different location
// than the original.
string linkFilename = file.Item["LinkFilename"] as string;
file.ParentFolder.Files.Add(linkFilename, mem, true);
}
catch (System.IO.FileFormatException)
{
return ModifyDocumentResults.InvalidFileFormat;
}
}
return ModifyDocumentResults.Success;
}