我目前有一个窗口表单,当按下一个按钮时,会将 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 =”,但我没有成功。
最佳答案
使用 getFiles
方法解决了问题
string[] filePaths = Directory.GetFiles(@"c:\Test\");
string[] documentsToMerge = filePaths;
string outputFileName = (@"C:\Test\Merge\Combined.docx");
MsWord.Merge(documentsToMerge, outputFileName, true);
谢谢你的帮助。
关于c# - 使用c#合并文件夹中的Word文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35982526/