Ich versuche den folgenden Code. Es nimmt einen fileName (docx Datei mit vielen Abschnitten) und ich versuche, durch jeden Abschnitt zu durchlaufen, der den Abschnittnamen erhält. Das Problem ist, dass ich am Ende nicht lesbare docx-Dateien bekomme. Es ist kein Fehler, aber ich denke, ich mache etwas falsch mit den Elementen in der Sektion.OpenXml Sdk - Kopieren von Abschnitten von docx in ein anderes docx
public void Split(string fileName) {
using (WordprocessingDocument myDoc =
WordprocessingDocument.Open(fileName, true)) {
string curCliCode = "";
MainDocumentPart mdp = myDoc.MainDocumentPart;
foreach (var element in mdp.Document.Body.ChildElements) {
if (element.Descendants().OfType<SectionProperties>().Count() == 1) {
//get the name of the section from the footer
var footer = (FooterPart) mdp.GetPartById(
element.Descendants().OfType<SectionProperties>().First().OfType
<FooterReference>().First().
Id.Value);
foreach (Paragraph p in footer.Footer.ChildElements.OfType<Paragraph>()) {
if (p.InnerText != "") {
curCliCode = p.InnerText;
}
}
if (curCliCode != "") {
var forFile = new List<OpenXmlElement>();
var els = element.ElementsBefore();
if (els != null) {
foreach (var e in els) {
if (e != null) {
forFile.Add(e);
}
}
for (int i = 0; i < els.Count(); i++) {
els.ElementAt(i).Remove();
}
}
Create(curCliCode, forFile);
}
}
}
}
}
private void Create(string cliCode,IEnumerable<OpenXmlElement> docParts) {
var parts = from e in docParts select e.Clone();
const string template = @"\Test\toSplit\blank.docx";
string destination = string.Format(@"\Test\{0}.docx", cliCode);
File.Copy(template, destination,true);
/* Create the package and main document part */
using (WordprocessingDocument myDoc =
WordprocessingDocument.Open(destination, true)) {
MainDocumentPart mainPart = myDoc.MainDocumentPart;
/* Create the contents */
foreach(var part in parts) {
mainPart.Document.Body.Append((OpenXmlElement)part);
}
/* Save the results and close */
mainPart.Document.Save();
myDoc.Close();
}
}
Weiß jemand, was das Problem sein könnte (oder wie man einen Abschnitt von einem Dokument in einen anderen korrekt kopiert)?
Gibt es gute Beispiele für ähnliche Dinge in OpenXml SDK? – jle