![](/img/trans.png)
[英]Merge multiple word documents into one using OpenXML and XElement
[英]OpenXML Merge Word Documents Formatting of multiple files
我有多個要合並在一起的docx模板文件。 如果第一個文件格式化為兩列,則在合並文件時,它將自動將下一個文件設置為多列word文檔,並更改格式,即使該文件先前是合並前的一列文件也是如此。 但是,當我首先選擇沒有多列的普通docx文件時,它會嘗試將所有多列文本設置為單列並更改格式。
我正在嘗試合並這些文檔,而無需更改任何格式。 到目前為止,這是我的代碼:
private void MergeDocuments()
{
bool docfilechecked = keepworddoc.Checked;
string caseno = casetextboxinput.Value;
string nameno = patentee;
string[] mergeFiles = Directory.GetFiles(directoryrootmerge + caseno + @"\", sequenceCounter + "*.doc*")
.Select(Path.GetFullPath)
.ToArray();
string filename = caseno + @" - " + nameno + " - PoA Form.docx";
string directory = directoryrootmerge + caseno;
string outputFileName = directoryrootmerge + caseno + @"\" + caseno + @" - " + nameno + " - PoA Form.docx";
//string outputFileName2 = directoryrootmerge + caseno + @"\" + caseno + @" - " + nameno + "- PoA Form.pdf";
if (mergeFiles.Length == 1)
{
System.IO.File.Copy(mergeFiles[0], outputFileName, true);
}
else
{
for (int i = 1; i < mergeFiles.Length; i++)
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(mergeFiles[0], true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
string altChunkId = "AltChunkId" + i;
//Append page break
Paragraph para = new Paragraph(new Run((new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page })));
mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = System.IO.File.Open(mergeFiles[i], FileMode.Open))
{
chunk.FeedData(fileStream);
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
//new page, if you like it...
//mainPart.Document.Body.AppendChild(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page })));
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
mainPart.Document.Save();
myDoc.Close();
System.IO.File.Copy(mergeFiles[0], outputFileName, true);
}
}
}
我在每個文件后添加了一個分頁符,以查看是否在合並時重置了格式但似乎不起作用-有人可以看到我可能要出問題的地方嗎?
您看過OpenXML PowerTools嗎? 它們包含用於組合OpenXML文檔的代碼...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.