1.添加系统引用Microsoft.Office.Interop.Word;
2.相关的函数说明
WdDocumentType 枚举 (Word)
指定文档类型。
名称 值 说明
wdTypeDocument 0 文档。
wdTypeFrameset 2 框架集。
wdTypeTemplate 1 模板。
2.Document.Select()方法
在使用此方法后,使用Selection属性处理文档
3.Document.Range 方法 (Word)
通过使用指定的开始和结束字符位置返回一个 Range 对象。
ActiveDocument.Range(Start:=0, End:=10).Bold = True
活动文档中的前 10 个字符设置加粗格式
4.相关的代码
private void button1_Click(object sender, EventArgs e)
{
object path = @"D:\Test合并word.doc";
List<string> pathList = new List<string>();
List<string> tihao = new List<string>();
pathList.Add(@"D:\1.doc");
pathList.Add(@"D:\2.doc");
for (int i = 1; i <= pathList.Count; i++)
{
string temp = i + "、 ";
tihao.Add(temp);
}
object objDocType = WdDocumentType.wdTypeDocument; // 指定文档类型(word文档)
object type = WdBreakType.wdSectionBreakContinuous;
Microsoft.Office.Interop.Word.Application wordApp; //Word应用程序变量
Document newWordDoc; //Word文档变量
object readOnly = false;
object isVisible = false;
wordApp = new ApplicationClass(); //初始化
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
newWordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
for (int i = 0; i < pathList.Count; i++)
{
Document openWord;
object obj = pathList[i];
openWord = wordApp.Documents.Open(ref obj, ref Nothing, ref readOnly, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref isVisible, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
openWord.Select();//在使用此方法之后,使用 Selection 属性处理文档。
openWord.Sections[1].Range.Copy();
//object start = 0;
//Range newRang = newWordDoc.Range(ref start, ref start);
// newWordDoc.Sections[1].Range.InsertBreak(ref type);//插入换行符
newWordDoc.Sections[1].Range.PasteAndFormat(WdRecoveryType.wdPasteDefault);//将剪切板上的内容以指定格式复制到指定的文档
newWordDoc.Sections[1].Range.InsertBefore(tihao[i]);
newWordDoc.Sections[1].Range.InsertBreak(ref type);//插入换行符
openWord.Close(ref Nothing, ref Nothing, ref Nothing);
}
object format = WdSaveFormat.wdFormatDocument;//.wdFormatDocumentD efault;
//将wordDoc文档对象的内容保存为DOCX文档
newWordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//关闭wordDoc文档对象
newWordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
MessageBox.Show("文件合并成功!");
}
更多精彩,敬请关注, 程序员导航网