DevPinoy.org
A Filipino Developers Community
   
How To: Merge Multiple Microsoft Word Documents in C#

"Combine. Merge. Join. Append. Concatenate. Microsoft Word Documents."

I had a pretty laidback today because one of my projects was halted due some requirements issue(we have just finished phase 1 and the client already wants to start phase 2 but they dont know what the want yet) so i was assigned to help one of my colleagues in a problem that they were having in their project. The problem was that they were trying to merge multiple Microsoft Word Documents into one file and for some reason the solution that they have implemented was not doing the job. They had this function that reads bits and bytes of the document and then combines those bytes into a single file. Yikes!

Their solution was messy... really really messy.

After hearing the problem I quickly realized that I have already done this in one of the projects i had with a previous employer. I know that i had some notes somewhere about how i solved it so I immediately went to my Gmail and started looking and voila! I found just what i needed! I wrote this class as a solution to a similar problem and the big difference with my implementation from what my officemate had in their project is that I am using the Microsoft Office Interop Assemblies which in their case is a suitable solution since their application is a Windows app running on the users desktop(if this is a web app they might have a problem because i know server admins who doesn't it when developers ask them to install MS Office to their production server).

Anyway, here's the class in its entirety. I added comments to explain what the function is doing and should be self-explanatory since I did'nt do anything fancy on it.

using System;
using Word = Microsoft.Office.Interop.Word;

namespace KeithRull.Utilities.OfficeInterop
{
    public class MsWord
    {
        /// <summary>
        /// This is the default Word Document Template file
        /// </summary>
        private const string defaultWordDocumentTemplate = @"Normal.dot";

        /// <summary>
        /// A function that merges Microsoft Word Documents that uses the default template
        /// </summary>
        /// <param name="filesToMerge">An array of files that we want to merge</param>
        /// <param name="outputFilename">The filename of the merged document</param>
        /// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param>
        public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
        {
            Merge(filesToMerge, outputFilename, insertPageBreaks, defaultWordDocumentTemplate);
        }

        /// <summary>
        /// A function that merges Microsoft Word Documents that uses a template specified by the user
        /// </summary>
        /// <param name="filesToMerge">An array of files that we want to merge</param>
        /// <param name="outputFilename">The filename of the merged document</param>
        /// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param>
        /// <param name="documentTemplate">The word document you want to use to serve as the template</param>
        public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
        {
            object defaultTemplate = documentTemplate;
            object missing = System.Type.Missing;
            object pageBreak = Word.WdBreakType.wdPageBreak;
            object outputFile = outputFilename;

            // Create  a new Word application
            Word._Application wordApplication = new Word.Application();

            try
            {
                // Create a new file based on our template
                Word._Document wordDocument = wordApplication.Documents.Add(
                                              ref defaultTemplate
                                            , ref missing
                                            , ref missing
                                            , ref missing);

                // Make a Word selection object.
                Word.Selection selection = wordApplication.Selection;

                // Loop thru each of the Word documents
                foreach (string file in filesToMerge)
                {
                    // Insert the files to our template
                    selection.InsertFile(
                                                file
                                            , ref missing
                                            , ref missing
                                            , ref missing
                                            , ref missing);

                    //Do we want page breaks added after each documents?
                    if (insertPageBreaks)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }

                // Save the document to it's output file.
                wordDocument.SaveAs(
                                ref outputFile
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing);

                // Clean up!
                wordDocument = null;
            }
            catch (Exception ex)
            {
                //I didn't include a default error handler so i'm just throwing the error
                throw ex;
            }
            finally
            {
                // Finally, Close our Word application
                wordApplication.Quit(ref missing, ref missing, ref missing);
            }
        }
    }
}

I gave them my file, showed them how to use it and save them the stress. Sweet! I hope this helps somebody in the future and if it does I hope they leave a comment too! Did you? :P

You can download the .cs file here MsWord.cs (4.5 KB). Please do remember that you need to add a reference to Microsoft.Office.Core for this class to work.


Posted 05-23-2007 4:21 PM by keithrull

Comments

Sasisekar wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-04-2007 1:45 AM

Hi

I am very happy such script is available

But I am a commoner, trying to use this function

that is, if I have a program that I can run which in turn executes this script to join files, that would be helpful

I do not know if I can use this in C program

I can write some C programs

Thanks and regards

Sasi

Abhi wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-05-2007 5:34 AM

hi..

This script works fine with my file system , and am thankful to you for that..

But when i post it on to the localhost to run the script, i am getting an COMexception...

the problem is with this :

Word._Document wordDocument = wordApplication.Documents.Add(

                                             ref defaultTemplate

                                           , ref missing

                                           , ref missing

                                           , ref missing);

after this code am using

Range rng;

object start = wordDocument.Content.Start;

its not creating the object and the "wordDocument" is showing null reference, whereby it should show "Microsoft.Interop.Office.Word.Document: or something...

Please guide me over this...

Thanks

Regards..

keithrull wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-05-2007 8:22 AM

@abhi: I think your problem is about DLL refferencing. Check to see if the server has the Microsoft Office Interop Assemblies installed in it.

@Sasisekar: You can convert this in C. All you need to do is refference the MS Office Dlls in your project and read it's contents. I wish i could help you in converting this in C but i can't since it has been a long time since i had my hands on C.

Abhi wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-05-2007 10:17 PM

I am new to .NET, and sorry if i sound stupid here, but i have installed Microsoft Office Interop Assemblies, which i have added as Referrence. Is that enough. I also checked DCOM config, where i found Microsoft Word Document, where by i gave all the access rights to see if it might not create any problem.

" Check to see if the server has the Microsoft Office Interop Assemblies installed in it."

please brief me with you above statement, i will be thankful to u...

Regards

Abhi

keithrull wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-08-2007 2:47 PM

Hmmm., I think theres something screwed up with your Office Assembly reference.

open your csproject file and check to see if the references looks similar to what i have(assuming that you have office 2003)

 <ItemGroup>

   <COMReference Include="Microsoft.Office.Core">

     <Guid>{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}</Guid>

     <VersionMajor>2</VersionMajor>

     <VersionMinor>3</VersionMinor>

     <Lcid>0</Lcid>

     <WrapperTool>primary</WrapperTool>

     <Isolated>False</Isolated>

   </COMReference>

   <COMReference Include="Word">

     <Guid>{00020905-0000-0000-C000-000000000046}</Guid>

     <VersionMajor>8</VersionMajor>

     <VersionMinor>3</VersionMinor>

     <Lcid>0</Lcid>

     <WrapperTool>primary</WrapperTool>

     <Isolated>False</Isolated>

   </COMReference>

 </ItemGroup>

Abhi... wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-08-2007 10:14 PM

This is my .cs file:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using Microsoft.Office.Interop.Word;

using System.IO;

public class MsWord

{

   private const string defaultWordDocumentTemplate = @"Normal.dot";

   private void Merge(string[] FilesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)

   {

       object defualtTemplate = documentTemplate;

       object missing = System.Type.Missing;

       object readOnly = false;

       object oTrue = true;

       object isVisible = true;

       object pagebreak = WdBreakType.wdPageBreak;

       object outputFile = outputFilename;

       Application wordApplication = new Application();

       try

       {

           Document wordDocument = wordApplication.Documents.Add(ref defualtTemplate,

                                               ref missing, ref missing, ref missing);

           Range rng;

           object start = wordDocument.Content.Start;

           object end = wordDocument.Content.End;

           // Supply a Start and End value for the Range.

           rng = wordDocument.Range(ref start, ref end);

           Object oUpperHeadingLevel = "1";

           Object oLowerHeadingLevel = "2";

           Object oTOCTableID = "TableOfContents";

           Selection selection = wordApplication.Selection;

           foreach (string file in FilesToMerge)

           {

               selection.InsertFile(file, ref missing, ref missing,

                                   ref missing, ref missing);

               if (insertPageBreaks)

               {

                   selection.InsertBreak(ref pagebreak);

               }

           }

           // Select the Range.

           rng.Select();

           // insert page numbers.

           wordApplication.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;

           wordApplication.Selection.TypeParagraph();

           String docNumber = "1";

           String revisionNumber = "0";

           wordApplication.Selection.Paragraphs.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;

           wordApplication.ActiveWindow.Selection.Font.Name = "Arial";

           wordApplication.Selection.Font.Size = 8;

           wordApplication.ActiveWindow.Selection.TypeText("Document #:" + docNumber + "-Revision #:" + revisionNumber);

           wordApplication.ActiveWindow.Selection.TypeText("\t");

           wordApplication.ActiveWindow.Selection.TypeText("\t");

           wordApplication.ActiveWindow.Selection.TypeText("Page ");

           object CurrentPage = WdFieldType.wdFieldPage;

           wordApplication.Selection.Fields.Add(wordApplication.Selection.Range, ref CurrentPage, ref missing, ref missing);

           wordApplication.ActiveWindow.Selection.TypeText(" of ");

           object TotalPages = WdFieldType.wdFieldNumPages;

           wordApplication.Selection.Fields.Add(wordApplication.Selection.Range, ref TotalPages, ref missing, ref missing);

           wordApplication.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;

           wordDocument.TablesOfContents[1].Update();

           wordDocument.TablesOfContents[1].UpdatePageNumbers();

           wordDocument.SaveAs(ref outputFile, ref missing, ref missing,

                               ref missing, ref missing, ref missing,

                               ref missing, ref missing, ref missing,

                               ref missing, ref missing, ref missing,

                               ref missing, ref missing, ref missing,

                               ref missing);

           wordDocument.Close(ref missing, ref missing, ref missing);

           wordApplication.Visible = true;

           wordApplication.Activate();

           wordDocument = wordApplication.Documents.Open(ref outputFile, ref missing, ref readOnly,

                            ref missing, ref missing, ref missing,

                            ref missing, ref missing, ref missing,

                            ref missing, ref missing, ref isVisible,

                            ref missing, ref missing, ref missing,

                            ref missing);

           wordDocument.Activate();

       }

       catch (Exception ex)

       {

       htthrow ex;

       }

   }

   public  void Merge(string FilesMerge, string outputFilename, bool insertPageBreaks)

   {

       string[] FilesToMerge = Directory.GetFiles(FilesMerge);

       Merge(FilesToMerge, outputFilename, insertPageBreaks, defaultWordDocumentTemplate);

   }

}

I have given both the reference of Microsoft.Word.Library and Microsoft.Office.Library

Erros that i been facing:

(1) The message filter indicated that the application is busy.(Exception from HRESULT; 0x8001010A(RPC_E_SERVERCALL_RETRYLATER))

i.e the word document opens, but doesnt show(it runs on the task manager

(2) "Word was unable to read this document.  It may be corrupt.\nTry one or more of the following:\n* Open and Repair the file.\n* Open the file with the Text Recovery converter."

(3) Word is unable to open the Document. COMException error...

(4) Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'Default'.

Source Error:

Line 1: <%@ Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="Default" %>

Line 2:

Line 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/.../xhtml1-transitional.dtd">

Source File: /test1/Default.aspx Line: 1

Sorry to bother u man, but this are the error i have faced, runs perfectly on filesystem, but not on http://localhost/

Hey do u think Word automation has some problem running on the Server-side...  i have heard, dont knw abt it...

Anyways thanks for helping buddy..

Catch u later...

Chao,

Regards

Abhi...

Keith Rull wrote [Updated] How To: Merge Multiple Microsoft Word Documents
on 06-09-2007 10:16 AM

A few weeks ago I wrote an article about merging word documents in C# and got great response about the

keithrull wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-09-2007 10:21 AM

Hi Abhi!

I found the issue and created a resolution for it. You can see it here:

devpinoy.org/.../updated-how-to-merge-multiple-microsoft-word-documents.aspx

Abhi wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-10-2007 11:39 PM

Hey Keith...

thanks a lot buddy, i did wht you said... but i am still in trouble...

the reason is, i still can open it through http://localhost...

it opens through http://localhost:1393 (just taking any arbitrary port)..

i dont knw the errors keeps on changing while i try n run it on server...

this time its :

"The message filter indicated that the application is busy. ( Excpetion from HRESULT 0x8001010A(RPC_E_SERVERCALL_RETRYLATER))"

The WINWORD.exe runs on Task manager as process, but doesnt open..

i dont knw whts happening and today i need to Run it on Win 2003 Server..

If u have a mial id, where i can send my whole project, that will be better, so u can try n run it on ur localhost, to see wht exactly is the problem..

thanks again..

regards

Abhi..

keithrull wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-11-2007 10:21 AM

You can send the project to me at keith[.]rull[@]gmail.com.

I'll look at it to see whats wrong with it. hopefully its not user permission. Have you tried the project i built in the updated article?

keithrull wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-11-2007 12:48 PM

i had the COM error appear awhie ago and this is how i solved it.

Add read-write permission to the folder to IUSR_*, Network_Service, ASPNET. Then, add this line to the web.config.

<identity impersonate="true"/>

After doing those steps i was able to run the merge application like a breeze.

HTH

Abhi wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-12-2007 12:44 AM

Hey Keith...

I have sent u the project...

please do the needful..

thanks

Abhi..

bejli wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-19-2007 6:28 AM

Hi Keith,

Your code works like a charm and is a great start for the application I am currently working on. But as I used your code, I have found a smaller bug...or maybe a lack of feature. The problem is that the code only inserts document text and does not preserve the page layout from the inserted document. In my project I have to combine multiple one page Word documents either in portrait or landscape page layout. I have searched on the web and couldn't come up with an idea how to implement page layout with the page break function. In Word ofcourse this is possible. Do you have any idea how I could read the page layout from documents for insertion and change the last page layout style, before inserting the text. Any help would be greatly appreciated couse it's driving me crazy.

tnx in advance,

Denis

L8A wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-26-2007 6:33 PM

You da' Man. Loved your simplistic code - This is exactly what I needed.. Thanks, buddy

MK wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 06-27-2007 12:28 AM

Hi Bejli,

You can control the page layout using wordDocument.PageSetup property:

//I saved page setup info in application settings file

private static void ApplyPageSetup(Word.Document document)

{

document.PageSetup.Orientation = Properties.Settings.Default.PageIsPortrait ? Word.WdOrientation.wdOrientPortrait : Word.WdOrientation.wdOrientLandscape;

       document.PageSetup.DifferentFirstPageHeaderFooter = Properties.Settings.Default.PageDifferentFirstPage;

       document.PageSetup.PageHeight = document.Application.InchesToPoints(Properties.Settings.Default.PageHeight);

       document.PageSetup.PageWidth = document.Application.InchesToPoints(Properties.Settings.Default.PageWidth);

       document.PageSetup.TopMargin = document.Application.InchesToPoints(Properties.Settings.Default.PageTopMargin);

       document.PageSetup.BottomMargin = document.Application.InchesToPoints(Properties.Settings.Default.PageBottomMargin);

       document.PageSetup.RightMargin = document.Application.InchesToPoints(Properties.Settings.Default.PageRightMargin);

       document.PageSetup.LeftMargin = document.Application.InchesToPoints(Properties.Settings.Default.PageLeftMargin);

       document.PageSetup.HeaderDistance = document.Application.InchesToPoints(Properties.Settings.Default.PageHeaderDistance);

document.PageSetup.FooterDistance = document.Application.InchesToPoints(Properties.Settings.Default.PageFooterDistance);

}

hope this helped.

Abhi wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 07-03-2007 7:39 AM

Hey Buddy...

Am back after a long time... ur application is working fine, but i have changed it into a Windows application, since the 2003 Server problem wasnt solved... Now i got to ask you something.. Here we do the merging from a single directory right... What if ther are several files in different directories, how will i define the path and merge those documents... Can u please give me an idea over this...

Thanks

Abhi...

bejli wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 07-08-2007 11:29 PM

Hey Abhi...

I am currently making an application where you have to merge files in different locations/directories. My way of doing it was like this: in first listbox window I show all the dirs or directory structure in the desired location/starting point which can be changed thrue textbox, in second checked listbox I show all the files in the selected directory from the first listbox (I get the selected dir with the listbox.Items.selected property into a string var), then I check all the files that I want to merge from current dir, and add them to the third listbox, in which i build up the path from the directory listbox, files checked listbox and the initial location from the textbox. So in third listbox I have all files with full paths. Next thing is to do a loop which merges all the files, and thats easy, since u have full paths to every file.

Hope this helps, if you need visual info, I can send you Project in progress.

Best regards,

bejli

Abhi wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 07-12-2007 10:31 PM

Hey Bejli..

thanks Buddy... but if u can send me ur project across, that will be of great help...

thanks a lot

Care...

Abhi..

bejli wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 07-20-2007 5:02 AM

Abhi,

sorry I was on bussines trip for awhile. Where do you wan't me to send you the project?

Abhi wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 07-22-2007 10:53 PM

hey Beji...

U can send it to me on pillaiabhilash@gmail.com

And one more thing which i wanted to discuss... Need badly help on it... This Merging works fine on my local filesystem.. But am Access files from portal server, using Oracle Drive.. Now if the add a new file to the FilesToMerge folder, then in the final merged file this new file should be placed at the end, but it doesnt happen it places itself in the first..

So i have to maintain a order to which it merges...

inshort Say ther is a database which has sequence of this files(paths) and i have to merged accordingly. Now if a new file is added.. it should be added at the end.. And if any exisiting file is edited.. it should not change its position in the final merged document..

I hope u getting wht i wanted to say...

hope u can guide me for this... Appreciated...

Abhi..

Grace Lin wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 11-02-2007 6:08 AM

Your code work excellent, anyway i need to implement it into web application (in the server). do you have any suggestion for this situation?

Keith Rull wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 11-02-2007 8:05 AM

you can implement the same code on a web app but bare in mind that the web application should have the proper permissions to generate and merge the word document. also, the office interop assemblies should exist on the server where the web application resides(this is normally an issue because most network admins don't allow office installed on their sever..)

Srini wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 11-28-2007 6:40 AM

Keith,

we have done this way. Do you see any problem with this approach.

public bool MergeDocuments(string targetFilePath, string[] sourceFiles, Microsoft.Office.Interop.Word.WdSectionStart sectionStartType)

       {

           if (targetFilePath == null || targetFilePath == string.Empty)

           {

               throw new ArgumentNullException("targetFilePath", "GApplication.Join: target file path is <null>/blank");

           }

           System.Diagnostics.Trace.WriteLine(DateTime.Now + ": Document merging started");

           object paramMissing = Type.Missing;

           object paramFalse = (object)false;

           object sectionStart = (Object)sectionStartType;

           object targetFile = (object)targetFilePath;

           object wordFormat = (object)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;

           Microsoft.Office.Interop.Word.Document doc = null;

           //Word.Section section = null;

           try

           {

               if (WordApp != null && this.IsActive)

               {

                   WordApp.Visible = false;

                   doc = WordApp.Documents.Add(ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);

                   if (doc != null)

                   {

                       doc.Activate();

                       int fileCout = sourceFiles.Length;

                       int fileIndex = 0;

                       foreach (String fileName in sourceFiles)

                       {

                           if (System.IO.File.Exists(fileName))

                           {

                               fileIndex++;

                               WordApp.Selection.InsertFile(fileName, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);

                               if (fileIndex < fileCout)

                               {

                                   WordApp.Selection.InsertBreak(ref sectionStart);

                               }

                           }

                       }

                       doc.SaveAs(ref targetFile, ref wordFormat, ref paramMissing,

                           ref paramMissing, ref paramMissing, ref paramMissing,

                           ref paramMissing, ref paramMissing, ref paramMissing,

                           ref paramMissing, ref paramMissing, ref paramMissing,

                           ref paramMissing, ref paramMissing, ref paramMissing,

                           ref paramMissing);

                       return true;

                   }

               }

           }

           catch (Exception ex)

           {

               doc.Saved = true;

               doc.Close(ref paramFalse, ref paramMissing, ref paramMissing);

               doc = null;

               System.Diagnostics.Trace.WriteLine(DateTime.Now + ": Document merging:" + ex.Message);

               throw ex;

           }

           finally

           {

               if (doc != null)

               {

                   doc.Close(ref paramMissing, ref paramMissing, ref paramMissing);

                   doc = null;

                   System.Diagnostics.Trace.WriteLine(DateTime.Now + ": Document merging completed");

               }

           }

           return false;

       }

keithrull wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 11-28-2007 4:58 PM

@Srini: Evrything looks good to me. Whats seems to be the problem with your code?

chimtu wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 01-08-2008 2:41 PM

Keith

Urs was the only hit I got close to for our requirement. We need o merge two word documents. That is our company sends out a word document to an outside user. They will make some changes, maybe add or delete some lines. When it comes back, the application should merge the new and old version and create a new version. Will your code do this?

I am a bit confused as I think ur code appends 1 file to the end of the old version.

Please reply at your earliest

Eduard wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 01-11-2008 3:45 PM

Intresting problem i have .. i run the code and it compiles .. it works beutifully on my computer .. but asoon as i put it across a newly installed machine it refuses to work .. says it cant find the assambly refference of microsoft.interop.word .. ive made sure the assemblies is installed so .. hmm what can the problem be?

keithrull wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 01-11-2008 4:20 PM

Do they have the same Office version?

Shree wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 01-17-2008 12:39 AM

Hi Keith,

Thanks a lot for excellent piece of code!

Just one question - is there any limit on how many documents can be merged using this approach?

I have a requirement which may need some 600-800 docs merging. Will that be feasible?

TIA,

Shree

JRadical wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 04-24-2008 11:46 AM

Blah...

Jag wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 05-14-2008 8:17 PM

Hi Keith,

Does this code help me in merging a template with a document with Content ?

Thanks

Jag

Adam wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 05-22-2008 3:12 AM

Hey Keith,

Your code is fantastic, has saved me much stress and confusion. However, I am getting a run-time error:

Exception System.Runtime.InteropServices.COMException was thrown in debuggee:

Word was unable to read this document.  It may be corrupt.

Try one or more of the following:

* Open and Repair the file.

* Open the file with the Text Recovery converter.

Merge() - j:\SharpDevelop\Projects\ReportEditor\MSWord.cs:99,13

Merge() - j:\SharpDevelop\Projects\ReportEditor\MSWord.cs:21,13

ok_Click() - j:\SharpDevelop\Projects\ReportEditor\ReportEditor.cs:178,7

OnClick()

OnClick()

OnMouseUp()

WmMouseUp()

WndProc()

WndProc()

WndProc()

OnMessage()

WndProc()

DebuggableCallback()

System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop()

RunMessageLoopInner()

RunMessageLoop()

Run()

Main() - j:\SharpDevelop\Projects\ReportEditor\ReportEditor.cs:17,4

Any idea what this is related to?

Adam wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 05-22-2008 3:14 AM

Hey Keith,

Your code is fantastic, has saved me much stress and confusion. However, I am getting a run-time error:

Exception System.Runtime.InteropServices.COMException was thrown in debuggee:

Word was unable to read this document.  It may be corrupt.

Try one or more of the following:

* Open and Repair the file.

* Open the file with the Text Recovery converter.

Merge() - j:\SharpDevelop\Projects\ReportEditor\MSWord.cs:99,13

Merge() - j:\SharpDevelop\Projects\ReportEditor\MSWord.cs:21,13

ok_Click() - j:\SharpDevelop\Projects\ReportEditor\ReportEditor.cs:178,7

OnClick()

OnClick()

OnMouseUp()

WmMouseUp()

WndProc()

WndProc()

WndProc()

OnMessage()

WndProc()

DebuggableCallback()

System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop()

RunMessageLoopInner()

RunMessageLoop()

Run()

Main() - j:\SharpDevelop\Projects\ReportEditor\ReportEditor.cs:17,4

Any idea what is causing this?

Thanks,

Adam

JMT wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 05-28-2008 9:13 PM

Hi Friends,

this Merge function is excellent. Thanks. I have different word documents with different Page headers. once i used this merge function, the files are merged but page headers disappered. Can you help me? Also how can we different levels (bullets) in our Document Creation using C#. (data are coming from DB. Can any one help me?

thanks in Advance.

JMT

zlatan24 wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 07-10-2008 10:33 AM

There is fine tool-<a href="www.recoverytoolbox.com/word_recovery.html">microsoft word text recovery</a>, can work with .doc, .docx, .dot and .dotx files and with any version of Microsoft Word text editor, can recover only plain text, it means, that text formatting, graphics and all other elements will be lost, can recover your data from corrupted *.doc files, located on corrupted media: floppy and CD disks, flash and zip drives, etc.,This tool can be used by anyone, your level of computer skills does not matter.

zlatan24 wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 07-10-2008 10:34 AM

There is fine tool--<a href="www.recoverytoolbox.com/word_recovery.html">microsoft word text recovery</a>, can work with .doc, .docx, .dot and .dotx files and with any version of Microsoft Word text editor, can recover only plain text, it means, that text formatting, graphics and all other elements will be lost, can recover your data from corrupted *.doc files, located on corrupted media: floppy and CD disks, flash and zip drives, etc.,This tool can be used by anyone, your level of computer skills does not matter.

Ben wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 08-20-2008 2:42 PM

Hi,

I have two docseach having 3 pages.

I want to append pages 2 and 3 of the second document after the 3rd  page of the first doc . Is this possible ?

Pleae Advice.

Peter wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 08-21-2008 12:42 AM

Hi,

this code also work fine for me execpt that the end document has double line distance-any1 got a clue what is wrong?

/Peter

Vadiraj wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 08-26-2008 2:09 AM

is it possible to merge two documents with PIA i mean without office installed can we use wordxml merges with the help of bookmarks

Jian wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 09-09-2008 8:13 AM

Hi,

I've tried your code. It's fine. But the Header of inserted file is lost.

I have a single page word document with Header. There are table

and logo in the Header. I just want to make a multi-page document

with that single file. That means, every page has the same content and header. Is it possible to keep the header by merge?

Thank you!

Sheetal wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 10-01-2008 1:41 AM

hi Abhi and Keith

I am trying to read and write the document which is stored in MOSS library.

For this i have created a usercontrol in asp.net.

It works fine when i run it in http://localhost but it doesnt work when i upload it to MOSS.

It gives error..Word was unable to read this document.  It may be corrupt.\nTry one or more of the following:\n* Open and Repair the file.\n* Open the file with the Text Recovery converter

Please let me know if you have found any solution.

Its very urgent.

I am trying it since last three days.

reza wrote re: How To: Merge Multiple Microsoft Word Documents in C#
on 11-15-2008 10:24 PM

how can i read textbox that exist in word(.doc) file or fill one label that existing in file with dynamic data. in word 2007 can do it with ContentControl but this instrument does not exists in word2003. please help me.

Copyright DevPinoy 2005-2008