2016-05-30 9 views
1

現在、ユーザーが複数のWord文書を1つにマージして、書式やヘッダーなどを失うことのないプログラムで作業しています。ドキュメントは、何も変更せずに、次々にスタックしていくだけです。ここで WordProcessingDocumentを使用して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; 
    } 
} 

ここでの問題は、フォーマットは、例えば第2の文書内の別のヘッダーがなることを意味し、最初の文書からコピーされ、すべての残りの部分に適用されていることです無視される。これをどうやって防ぐのですか?

私は、sectionMarkValues.NextPageを使用してセクションにドキュメントを分割し、altChunkを使用することを検討しています。

後者の問題は、altChunkはMemoryStreamを "FeedData"メソッドに処理できないようです。

+0

あなたのSendDataオブジェクトが何のために働きますか? –

+0

SendDataタイプには、プログラムで後で使用される情報(ファイルをディスクに保存するか電子メールで送信するかなど)が含まれます。マージには、バイト配列形式のドキュメントを含むFile属性のみが必要です。 –

答えて

0

DocIOは、Word 2003/2007/2010/2013/2016ファイルの読み取り、書き込み、マージ、レンダリングができる.NETライブラリです。あなたが資格を得るならば、コントロールの全スイートはcommunity license programを介して無料で(商用アプリケーションも)利用可能です。コミュニティライセンスは、制限や透かしのない完全な製品です。

ステップ1:コンソールアプリケーションを作成
ステップ2Syncfusion.DocIO.Base、Syncfusion.Compression.BaseSyncfusion.OfficeChart.Baseへの参照を追加します。 NuGetを使用してこれらの参照をプロジェクトに追加することもできます。
ステップ3:&に次のコードスニペットを貼り付けます。

このコードスニペットは、要件に応じてドキュメントを生成します。各入力Word文書は、元の書式、スタイル、ヘッダー/フッターとマージされます。

Downloadable Demo

using Syncfusion.DocIO.DLS; 
using Syncfusion.DocIO; 
using System.IO; 

namespace DocIO_MergeDocument 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     //Boolean to indicate whether any of the input document has different odd and even headers as true 
     bool isDifferentOddAndEvenPagesEnabled = false; 
     // Creating a new document. 
     using (WordDocument mergedDocument = new WordDocument()) 
     { 
      //Get the files from input directory 
      DirectoryInfo dirInfo = new DirectoryInfo(System.Environment.CurrentDirectory + @"\..\..\Data"); 
      FileInfo[] fileInfo = dirInfo.GetFiles(); 
      for (int i = 0; i < fileInfo.Length; i++) 
      { 
       if (fileInfo[i].Extension == ".doc" || fileInfo[i].Extension == ".docx") 
       { 
        using (WordDocument sourceDocument = new WordDocument(fileInfo[i].FullName)) 
        { 
         //Check whether the document has different odd and even header/footer 
         if (!isDifferentOddAndEvenPagesEnabled) 
         { 
          foreach (WSection section in sourceDocument.Sections) 
          { 
           isDifferentOddAndEvenPagesEnabled = section.PageSetup.DifferentOddAndEvenPages; 
           if (isDifferentOddAndEvenPagesEnabled) 
            break; 
          } 
         } 
         //Sets the breakcode of First section of source document as NoBreak to avoid imported from a new page 
         sourceDocument.Sections[0].BreakCode = SectionBreakCode.EvenPage; 
         //Imports the contents of source document at the end of merged document 
         mergedDocument.ImportContent(sourceDocument, ImportOptions.KeepSourceFormatting); 
        } 
       } 
      } 
      //if any of the input document has different odd and even headers as true then 
      //Copy the content of the odd header/foort and add the copied content into the even header/footer 
      if (isDifferentOddAndEvenPagesEnabled) 
      { 
       foreach (WSection section in mergedDocument.Sections) 
       { 
        section.PageSetup.DifferentOddAndEvenPages = true; 
        if (section.HeadersFooters.OddHeader.Count > 0 && section.HeadersFooters.EvenHeader.Count == 0) 
        { 
         for (int i = 0; i < section.HeadersFooters.OddHeader.Count; i++) 
          section.HeadersFooters.EvenHeader.ChildEntities.Add(section.HeadersFooters.OddHeader.ChildEntities[i].Clone()); 
        } 
        if (section.HeadersFooters.OddFooter.Count > 0 && section.HeadersFooters.EvenFooter.Count == 0) 
        { 
         for (int i = 0; i < section.HeadersFooters.OddFooter.Count; i++) 
          section.HeadersFooters.EvenFooter.ChildEntities.Add(section.HeadersFooters.OddFooter.ChildEntities[i].Clone()); 
        } 
       } 
      } 
      //If there is no document to merge then add empty section with empty paragraph 
      if (mergedDocument.Sections.Count == 0) 
       mergedDocument.EnsureMinimal(); 
      //Saves the document in the given name and format 
      mergedDocument.Save("result.docx", FormatType.Docx); 
     } 
    } 
} 

} 

注:奇数および偶数ページに対して異なるヘッダー/フッターを適用 のWord文書(いないセクション)レベルの設定があります。各入力 は、このプロパティに対して異なる値を持つことができます。 入力文書のいずれかに、奇数偶数ヘッダー/フッターが真で​​ある場合は、 文書のヘッダー/フッターの外観に影響します。したがって、入力文書のいずれかに異なる奇数と の偶数ヘッダー/フッターがある場合、結果のWord文書は が奇数ヘッダー/フッターの内容に置き換えられます。

DocIOの詳細については、当社help documentation

を参照してください。私はSyncfusion

関連する問題