读取段落或表格中的表单字段值

时间:2019-07-08 10:22:06

标签: c# ms-word interop

我需要阅读Word文件的内容,并且根据一些特定的要求,我需要将Word文件的内容插入到SQL Server DB中。

我正在使用Microsoft.Office.Interop.Word dll。我已经通过Visual Studio(IDE)中的管理nuget软件包对其进行了更新。

在单词中找到整行时,它读起来很好。当它在表或段落中发现任何表单控件时,就会出现问题。

我希望它首先检测表单控件类型(复选框,文本框,下拉列表,日期ticker),然后找到其值。

当前,当它找到任何表单字段时,将显示“ \ u0015”作为文本。

如何读取段落或表中的表单控件值。

我还需要找到一种方法来读取单词文件。

第1段 第2段 表格1 表2 第1段

进入段落或表后,我可以读取特定的控制值(如果存在),否则可以读取简单的字符串。

目前,我正在为段落和表格使用两个单独的循环。

我正在使用以下代码:

    StringBuilder text = new StringBuilder();
    List<Range> TablesRanges = new List<Range>();
    string celltext = string.Empty;

    Microsoft.Office.Interop.Word.Application wordApp = new Application();
    object file = @"D:\Test.docx";

    object nullobj = System.Reflection.Missing.Value;

    Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(
    ref file, ref nullobj, ref nullobj,
                                          ref nullobj, ref nullobj, ref nullobj,
                                          ref nullobj, ref nullobj, ref nullobj,
                                          ref nullobj, ref nullobj, ref nullobj);

    text.Append("Paragraph Start\n");
    foreach (Microsoft.Office.Interop.Word.Paragraph paragraph in doc.Paragraphs)
    {
        if (!string.IsNullOrEmpty(paragraph.Range.Text) && !paragraph.Range.Text.Contains("\r\a"))
        {
            string toWrite = paragraph.Range.Text;
            text.Append(toWrite.Replace('\r', ' ').Replace('\n', ' ').Replace('\a', ' ') + " \n"); 

            foreach (Field field in doc.Fields)
            {
               var j=  field.Result.ContentControls.GetType();

                //Here I want it check the control type first then get its value
                if (field.Result != null)
                {
                    var m = field.Result.Text;
                }

            }
        }
    }
    text.Append("Paragraph End\n");

    text.Append("Table Start\n");
    foreach (Microsoft.Office.Interop.Word.Table tb in doc.Tables)
    {
        for (int row = 1; row <= tb.Rows.Count; row++)
        {
            for (int index = 1; index <= 20; index++)
            {
                try
                {                     
                    var cell = tb.Cell(row, index);

                    celltext += cell.Range.Text + " ";
                }
                catch (Exception ex)
                {
                    break;
                }
            }

            text.Append(celltext.Replace('\r', ' ').Replace('\n', ' ').Replace('\a', ' ') + " \n");
            celltext = "";               
        }

        text.Append("\n");
    }
    text.Append("Table End");

    ReadContent(text.ToString());
    text.Clear();

0 个答案:

没有答案