近段时间在公司遇到一个问题,需要把所有的word文件进行合并,形成一个word文件便于打印,主要解决的是成批量的文件的时候,如果一个个操作的话,会非常的繁琐。
需要引用using Microsoft.Office.Interop.Word;
忘记是看哪位大神的博客了,在此贴出来,以便于其它同仁能够借鉴,如有侵权等,请联系本人,在此向借鉴的大神表示歉意。FolderBrowserDialog dialog = new FolderBrowserDialog
{
Description = @"请选择文件路径"
};
if (dialog.ShowDialog() != DialogResult.OK) return;
string foldPath = dialog.SelectedPath;
DirectoryInfo folder = new DirectoryInfo(foldPath);
FileInfo[] files = folder.GetFiles();
var app = new Microsoft.Office.Interop.Word.Application();
var doc = app.Documents.Add();
foreach (var d in files)
{
if (d.Extension == ".doc")
{
app.Selection.InsertFile(d.FullName);
}
else if (d.Extension == ".jpg" || d.Extension == ".png")
{
object linkToFile = false;
object saveWithDocument = true;
object anchor = app.Selection.Range;
app.ActiveDocument.InlineShapes.AddPicture(d.FullName, ref linkToFile, ref saveWithDocument, ref anchor);
app.ActiveDocument.InlineShapes[1].Width = 300f;//图片宽度
app.ActiveDocument.InlineShapes[1].Height = 400f;//图片高度
}
//app.Selection.InsertBreak(WdBreakType.wdPageBreak);
}
doc.SaveAs(FileName: Path.Combine(folder.FullName, "最终合并.docx"));
doc.Close();
app.Quit();