使用C#合并文件夹中的Word文档

6

我目前拥有一个窗体,当按下按钮时,它会将3个单独的word docx文件合并成一个组合文件。

 private void button1_Click(object sender, EventArgs e)
    {

            string document1 = @"C:\Test\Test1.docx";
            string document2 = @"C:\Test\Test2.docx";
            string document3 = @"C:\Test\Test3.docx";

            string[] documentsToMerge = { document1, document2, document3 };

            string outputFileName = String.Format(@"C:\Test\Merge\Combined.docx", Guid.NewGuid());

            MsWord.Merge(documentsToMerge, outputFileName, true);}

然而,我希望选择包含文件夹(“C:\ Test”)而不是每个单独的文件。这将允许我合并更多文件,而无需将它们逐个编码到程序中,这样在使用时就更加实用。

有没有建议如何实现这一点?

public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
    {
        object defaultTemplate = documentTemplate;
        object missing = System.Type.Missing;
        object pageBreak = Word.WdBreakType.wdSectionBreakNextPage;
        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 missing
                                        , ref missing
                                        , ref missing
                                        , ref missing);

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

            //Count the number of documents to insert;
            int documentCount = filesToMerge.Length;

            //A counter that signals that we shoudn't insert a page break at the end of document.
            int breakStop = 0;

            // Loop thru each of the Word documents
            foreach (string file in filesToMerge)
            {
                breakStop++;
                // 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 && breakStop != documentCount)
                {
                    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);
        }
    }
}

这是第一部分代码中引用的MsWord.merge。我尝试使用“ lnkResult.NavigateUrl =”,但未成功。


你可以获取目录中的*.docx文件,并将其用作数组列表。 - BugFinder
你能详细解释一下你的意思吗?你的意思是: string[] GetFiles( string path (C:/Test/) - cgraham720
实际上,我已经解决了这个问题,getfiles方法完美地工作了。谢谢 - 我会标记为已解决。 - cgraham720
https://dev59.com/_mYr5IYBdhLWcg3w6eI3 - Mafii
这与 MS-Word 没有任何关系。 - Rahul
1
如果我没错的话,String.Format(@"C:\Test\Merge\Combined.docx", Guid.NewGuid()); 这里使用 String.Format() 是完全没有意义的... - Felix D.
2个回答

3

使用getFiles方法解决了问题。

string[] filePaths = Directory.GetFiles(@"c:\Test\");

string[] documentsToMerge = filePaths;

string outputFileName = (@"C:\Test\Merge\Combined.docx");

MsWord.Merge(documentsToMerge, outputFileName, true);

感谢您的帮助。

.GetFiles()中指定一个搜索模式怎么样,因为他只想要Word文档.... => https://msdn.microsoft.com/de-de/library/ms143316%28v=vs.110%29.aspx - Felix D.
1
@fede - 好主意,我现在会尝试一下。我猜你可以过滤两种类型?以允许doc和docx? - cgraham720

2

GetFiles() 会获取所有文件,因此第二个重载更适合。为获取所有 Word 文档(*.doc*.docx),请调用:

//Add *.doc
string[] allWordDocuments = Directory.GetFiles("YourDirectory", "*.doc", SearchOptions.AllDirectorys); //Or if you want only SearchOptions.TopDirectoryOnly

NineBerry在他的评论中提到的,这也将包括*.docx!!!
这将获取所有*.doc & *.docx文件,并忽略所有其他文件类型。 这将避免错误,因为GetFiles("DirectoryName")会获取所有文件,这可能会导致在传递文件(例如*.exe)时在MsWord.Merge()中出现错误。
所以一个简单的方法是:
string outputPath = @"C:\Test\Merge\Combined.docx";

MsWord.Merge(allWordDocuments, outputPath, true); 

1
你不需要两次调用GetFiles()。如果你使用带有恰好三个字符的扩展名的GetFiles(),那么以这三个字符开头的更长扩展名的文件也会被找到!因此,答案中的当前版本会返回一些文件两次。 - NineBerry
@nineberry - 感谢您的建议,我只是在我的文件路径末尾添加了(@"c:\Test", "*.doc"); - 现在它包括 .doc 和 docx。 - cgraham720

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接