c# - 使用 Microsoft.Office.Interop.Word 解析表,只从第一列获取文本?

标签 c# ms-office office-interop

我正在编写一个程序来解析 Microsoft Word 2010 文档中的文本数据。具体来说,我想从文档中每个表格第一列的每个单元格中获取文本。

作为引用,文档如下所示: enter image description here

我只需要每页第一列单元格中的文本。我要将此文本添加到内部数据表中。

到目前为止,我的代码如下所示:

private void button1_Click(object sender, EventArgs e)
    {
        // Create an instance of the Open File Dialog Box
        var openFileDialog1 = new OpenFileDialog();

        // Set filter options and filter index
        openFileDialog1.Filter = "Word Documents (.docx)|*.docx|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.Multiselect = false;

        // Call the ShowDialog method to show the dialog box.
        openFileDialog1.ShowDialog();
        txtDocument.Text = openFileDialog1.FileName;

        var word = new Microsoft.Office.Interop.Word.Application();
        object miss = System.Reflection.Missing.Value;
        object path = openFileDialog1.FileName;
        object readOnly = true;
        var docs = word.Documents.Open(ref path, ref miss, ref readOnly, 
                                       ref miss, ref miss, ref miss, ref miss, 
                                       ref miss, ref miss, ref miss, ref miss, 
                                       ref miss, ref miss, ref miss, ref miss, 
                                       ref miss);

        // Datatable to store text from Word doc
        var dt = new System.Data.DataTable();
        dt.Columns.Add("Text");

        // Loop through each table in the document, 
        // grab only text from cells in the first column
        // in each table.
        foreach (Table tb in docs.Tables)
        {
            // insert code here to get text from cells in first column
            // and insert into datatable.
        }

        ((_Document)docs).Close();
        ((_Application)word).Quit();
    }

我卡在从每个单元格中获取文本并将其添加到我的数据表的部分。有人可以给我一些指示吗?我一定会很感激。

谢谢!

最佳答案

我不知道你想如何将它存储在你的数据库中,但为了阅读文本,我认为你可以循环出行并选择每行中的第一列:

foreach (Table tb in docs.Tables) {
    for (int row = 1; row <= tb.Rows.Count; row++) {
        var cell = tb.Cell(row, 1);
        var text = cell.Range.Text;

        // text now contains the content of the cell.
    }
}

关于c# - 使用 Microsoft.Office.Interop.Word 解析表,只从第一列获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17795717/

相关文章:

c# - EF Core - 在上一个操作完成之前,在此上下文中启动了第二个操作。不保证任何实例成员都是线程安全的

c# - C# 中的可空 DateTime

c# - 使用 AddRange() 时如何增加 List<T> 的内部数组

c# - 在引用列表中找不到 Microsoft.Office.Interop.Word

javascript - 您可以在 OS X 上安装用 JavaScript 编写的 Office 应用程序加载项吗

c# - 从多个线程访问 word 文档的单词列表

c# - 用于简单实时圆检测的霍夫变换替代方案

c# - 在 C# 中访问打开的 Excel 工作簿

c# - 在 Excel 功能区上,如何将按钮一直对齐到右侧?

c# - 如何检查形状是否具有正确的链接