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

前端之家收集整理的这篇文章主要介绍了c# – 从单词文档逐行读取前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图用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();

猜你在找的C#相关文章