【发布时间】:2016-05-30 14:37:10
【问题描述】:
我目前正在开发一个程序,在该程序中,用户应该能够将多个 Word 文档合并为一个,而不会丢失任何格式、标题等。文档应该一个接一个地简单地堆叠起来,没有任何变化。
这是我当前的代码:
public virtual Byte[] MergeWordFiles(IEnumerable<SendData> sourceFiles)
{
int f = 0;
// If only one Word document then skip merge.
if (sourceFiles.Count() == 1)
{
return sourceFiles.First().File;
}
else
{
MemoryStream destinationFile = new MemoryStream();
// Add first file
var firstFile = sourceFiles.First().File;
destinationFile.Write(firstFile, 0, firstFile.Length);
destinationFile.Position = 0;
int pointer = 1;
byte[] ret;
// Add the rest of the files
try
{
using (WordprocessingDocument mainDocument = WordprocessingDocument.Open(destinationFile, true))
{
XElement newBody = XElement.Parse(mainDocument.MainDocumentPart.Document.Body.OuterXml);
for (pointer = 1; pointer < sourceFiles.Count(); pointer++)
{
WordprocessingDocument tempDocument = WordprocessingDocument.Open(new MemoryStream(sourceFiles.ElementAt(pointer).File), true);
XElement tempBody = XElement.Parse(tempDocument.MainDocumentPart.Document.Body.OuterXml);
newBody.Add(XElement.Parse(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(new Break { Type = BreakValues.Page })).OuterXml));
newBody.Add(tempBody);
mainDocument.MainDocumentPart.Document.Body = new Body(newBody.ToString());
mainDocument.MainDocumentPart.Document.Save();
mainDocument.Package.Flush();
}
}
}
catch (OpenXmlPackageException oxmle)
{
throw new Exception(string.Format(CultureInfo.CurrentCulture, "Error while merging files. Document index {0}", pointer), oxmle);
}
catch (Exception e)
{
throw new Exception(string.Format(CultureInfo.CurrentCulture, "Error while merging files. Document index {0}", pointer), e);
}
finally
{
ret = destinationFile.ToArray();
destinationFile.Close();
destinationFile.Dispose();
}
return ret;
}
}
这里的问题是格式从第一个文档复制并应用于所有其余文档,这意味着例如第二个文档中的不同标题将被忽略。如何防止这种情况发生?
我一直在考虑使用 SectionMarkValues.NextPage 以及使用 altChunk 将文档分成多个部分。
后者的问题是 altChunk 似乎无法将 MemoryStream 处理到它的“FeedData”方法中。
【问题讨论】:
-
你的 SendData 对象是什么?
-
SendData 类型包含稍后在程序中使用的信息(例如文件是否应该保存到光盘或通过电子邮件发送)。合并只需要 File 属性,该属性包含字节数组格式的文档。