gpt4 book ai didi

c# - 逐行读取word文档

转载 作者:可可西里 更新时间:2023-11-01 03:06:25 28 4
gpt4 key购买 nike


我正在尝试使用 C# 阅读 word 文档。我能够获取所有文本,但我希望能够逐行阅读存储在列表中并绑定(bind)到 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, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, 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, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, 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# - 逐行读取word文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555064/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com