加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从单词文档逐行读取

发布时间:2020-12-15 06:50:41 所属栏目:百科 来源:网络整理
导读:我试图用C#读一个word文档.我能够获取所有文本,但我想要逐行读取并存储在列表中并绑定到gridview.目前,我的代码只返回一个项目列表,只有所有文本(不是按需要逐行).我正在使用Microsoft.Office.Interop.Word库来读取该文件.以下是我现在的代码: Application
我试图用C#读一个word文档.我能够获取所有文本,但我想要逐行读取并存储在列表中并绑定到gridview.目前,我的代码只返回一个项目列表,只有所有文本(不是按需要逐行).我正在使用Microsoft.Office.Interop.Word库来读取该文件.以下是我现在的代码:
Application word = new Application();
    Document doc = new Document();

    object fileName = path;
    // Define an object to pass to the API for missing parameters
    object missing = System.Type.Missing;
    doc = word.Documents.Open(ref fileName,ref missing,ref missing);

    String read = string.Empty;
    List<string> data = new List<string>();
    foreach (Range tmpRange in doc.StoryRanges)
    {
        //read += tmpRange.Text + "<br>";
        data.Add(tmpRange.Text);
    }
    ((_Document)doc).Close();
    ((_Application)word).Quit();

    GridView1.DataSource = data;
    GridView1.DataBind();

解决方法

好.我找到了解决方案 here.

最后的代码如下:

Application word = new Application();
    Document doc = new Document();

    object fileName = path;
    // Define an object to pass to the API for missing parameters
    object missing = System.Type.Missing;
    doc = word.Documents.Open(ref fileName,ref missing);

    String read = string.Empty;
    List<string> data = new List<string>();
    for (int i = 0; i < doc.Paragraphs.Count; i++)
    {
        string temp = doc.Paragraphs[i + 1].Range.Text.Trim();
        if (temp != string.Empty)
            data.Add(temp);
    }
    ((_Document)doc).Close();
    ((_Application)word).Quit();

    GridView1.DataSource = data;
    GridView1.DataBind();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读