分享

C#读取Word文档内容 | 胡航飞博客

 木棉下的守望 2014-11-04

C#读取Word文档内容代码


首先要添加引用com组件:
wordcom
然后引用:
C#
1
using Word = Microsoft.Office.Interop.Word;

获取内容:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
        /// <summary>
        /// 读取 word文档 返回内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetWordContent(string path)
        {
            try
            {
                Word.Application app = new Microsoft.Office.Interop.Word.Application();
                Type wordType = app.GetType();
                Word.Document doc = null;
                object unknow = Type.Missing;
                app.Visible = false;
                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);
                int count = doc.Paragraphs.Count;
                StringBuilder sb = new StringBuilder();
                for (int i = 1; i <= count; i++)
                {
                    
                        sb.Append(doc.Paragraphs[i].Range.Text.Trim());
                }
                
                doc.Close(ref unknow, ref unknow, ref unknow);
                wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, app, null);
                doc = null;
                app = null;
                //垃圾回收
                GC.Collect();
                GC.WaitForPendingFinalizers();
                string temp=sb.ToString();
                //if (temp.Length > 200)
                //    return temp.Substring(0, 200);
                //else
                    return temp;
            }
            catch
            {
                return "";
            }
        }

转载文章请注明,转载自:胡航飞博客 [http://www.]

原文链接:http://www./program/csharp-504.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多