我正在合并几个 docx 文件,这些文件是通过 C# 使用 openxml 和 wordml 创建的。标题标签为标题 1 、标题 2 等的文件以及带有这些标签的一些文本。当这些文件被单独创建时,如果我们单击或选择那些标记有标题 1 和标题 2 的文本,那么标题 1、标题 2 等会被突出显示,并且导航盘也会显示在标题 1、标题 2 标记上,但是在合并这些文档后,当我们单击或选择这些文本时,标题 1 和标题 2 并没有突出显示。在样式功能区。此处给出了该合并的代码,
MemoryStream ms = new MemoryStream();
using (WordprocessingDocument myDoc =
WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
mainPart.Document = new Document { Body = new Body() };
int counter = 1;
foreach (var sectionOutput in sectionOutputs)
{
foreach (var outputFile in sectionOutput.Files)
{
Paragraph sectionBreakPara = null;
if (!sectionOutput.SectionType.Equals(sectionOutputs[sectionOutputs.Count - 1].SectionType))
{
if (outputFile == sectionOutput.Files.Last())
//check whether this is the last file in this section
{
using (
WordprocessingDocument pkgSourceDoc =
WordprocessingDocument.Open(outputFile.OutputStream, true))
{
var sourceBody = pkgSourceDoc.MainDocumentPart.Document.Body;
SectionProperties docSectionBreak =
sourceBody.Descendants<SectionProperties>().LastOrDefault();
if (docSectionBreak != null)
{
var clonedSectionBreak = (SectionProperties)docSectionBreak.CloneNode(true);
clonedSectionBreak.RemoveAllChildren<FooterReference>();
clonedSectionBreak.RemoveAllChildren<HeaderReference>();
sectionBreakPara = new Paragraph();
ParagraphProperties sectionParaProp = new ParagraphProperties();
sectionParaProp.AppendChild(clonedSectionBreak);
sectionBreakPara.AppendChild(sectionParaProp);
}
}
}
}
string altChunkId = string.Format("altchunkId{0}", counter);
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
outputFile.OutputStream.Seek(0, SeekOrigin.Begin);
chunk.FeedData(outputFile.OutputStream);
AltChunk altChunk = new AltChunk(new AltChunkProperties(new MatchSource { Val = new OnOffValue(true) })) { Id = altChunkId };
mainPart.Document.Body.AppendChild(altChunk);
if (sectionBreakPara != null)
{
mainPart.Document
.Body
.AppendChild(sectionBreakPara);
}
counter++;
}
}
mainPart.Document.Save();
}
return ms;