word文档操作
0、文档操作之前引用声明部分
using Microsoft.Office.Core;
using Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;
Object Nothing = System.Reflection.Missing.Value;
object filename = "D:\\aa.docx";
Word._Document oDoc = null;
Word.Document WordDoc = null;
Word.Application WordApp = null;
1.创建word文档
Word.Application WordApp = new Word.ApplicationClass();
Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
2、打开word文档
Word._Application oword = new Word.Application();
//属性,可以根据需要设
object readOnly = false;
oword.Visible = true;
oDoc = oword.Documents.Open(ref filename, ref Nothing, ref readOnly, 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);
//打印文档中的文字部分
Console.WriteLine(oDoc.Content.Text as string );
//在文档中最前面插入内容
Word.Range p_range = oDoc.Paragraphs[1].Range;
p_range.Text = "本句话将加在文档内容最前面";
//在文档最后面加内容
oDoc.Paragraphs.Last.Range.Text = "该句话将加在文档内容最后面";
//激活改word文档,使其显示出来
oDoc.Activate();
3、保存和关闭word文档
//保存文档
WordDoc.SaveAs(ref filename, 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, ref Nothing);
//关闭文档
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
注意:操作word文档时要引用自己正在用的word文件的MSWORD.OLB因为不同版本里的word文件的MSWORD.OLB不相同。该文件一般都在word文件的安装文件里。本文上传的是07版word的MSWORD.OLB