C#读取word文档中的内容

时间:2017-01-11  |  来源:cnphp6

原文地址 http://blog.csdn.net/yhrun/article/details/7674540

在使用前需要添加引用巨硬的com组件:Microsoft Word 12.0 object library    ^^^^^2007对应的是12.0的

添加引用→COM→选择Microsoft Word 12.0 object library

然后在namespace上面写下:using Word = Microsoft.Office.Interop.Word;

这样,添加引用就算OK了

protected void Button7_Click(object sender, EventArgs e)
        {
            string path = @"F:\面试所需知识点.docx";
            Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Word.Document doc = null;
            object unknow = Type.Missing;
            //object nullobj = System.Reflection.Missing.Value;
            app.Visible = true;            
            object file = path;
            doc = app.Documents.Open(ref file,
                ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow);
            string temp = doc.Paragraphs[1].Range.Text.Trim();//读取第一段内容
            string a = doc.Content.Text;//读取整篇文档的内容            
            doc.Close(ref unknow, ref unknow, ref unknow);//关闭文件
            app.Quit(ref unknow, ref unknow, ref unknow);//关闭COM
        }