Combining Word documents (Office Interop & .NET), saving formatting

I find it difficult to merge multiple text documents together using Microsoft Office Interop Assemblies (Office 2007) and ASP.NET 3.5. I can combine documents, but some of my formatting is missing (namely, fonts and images).

My current merge code is shown below.

private void CombineDocuments() {
        object wdPageBreak = 7;
        object wdStory = 6;
        object oMissing = System.Reflection.Missing.Value;
        object oFalse = false;
        object oTrue = true;
        string fileDirectory = @"C:\documents\";

        Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document wDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

        string[] wordFiles = Directory.GetFiles(fileDirectory, "*.doc");
        for (int i = 0; i < wordFiles.Length; i++) {
            string file = wordFiles[i];
            wDoc.Application.Selection.Range.InsertFile(file, ref oMissing, ref oMissing, ref oMissing, ref oFalse);
            wDoc.Application.Selection.Range.InsertBreak(ref wdPageBreak);
            wDoc.Application.Selection.EndKey(ref wdStory, ref oMissing);
        }
        string combineDocName = Path.Combine(fileDirectory, "Merged Document.doc");
        if (File.Exists(combineDocName))
            File.Delete(combineDocName);
        object combineDocNameObj = combineDocName;
        wDoc.SaveAs(ref combineDocNameObj, ref m_WordDocumentType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    } 

I don’t care how it is done. It can be output via PDF, if necessary. I just want the formatting to be portable.

+3
source share
1 answer

When adding documents, you skip the template name, so ut is not formatted enough.

It should look like

string defaultTemplate="your template name with full path"; 

OR

string defaultTemplate="Normal.dot";

wordApplication.Documents.Add(ref defaultTemplate,............

Ref: http://devpinoy.org/blogs/keithrull/archive/2007/05/23/how-to-merge-multiple-microsoft-word-documents-in-c.aspx

-1

Source: https://habr.com/ru/post/1738427/


All Articles