0

I had a Word document that contains data for several products. Each product contains a specification table, and I want to create a windows application to search for product name and extract its table data using c#.

using (var doc = WordprocessingDocument.Open(@"C:\reader\Sample2xml.xml", false))
{
    // To create a temporary table   
    DataTable dt = new DataTable();
    int rowCount = 0;
     
    // Find the first table in the document.   
    Table table = doc.MainDocumentPart.Document.Elements<Table>().First();
   
    // To get all rows from table  
    IEnumerable<TableRow> rows = table.Elements<TableRow>();
     
    // To read data from rows and to add records to the temporary table  
    foreach (TableRow row in rows)
    {
        if (rowCount == 0)
        {
            foreach (TableCell cell in row.Descendants<TableCell>())
            {
               dt.Columns.Add(cell.InnerText);
            }
            rowCount += 1;
            }
            else
            {
            dt.Rows.Add();
            int i = 0;
            foreach (TableCell cell in row.Descendants<TableCell>())
              {
               dt.Rows[dt.Rows.Count - 1][i] = cell.InnerText;
               i++;
              }
            }
    }

What I need to do is to search for product name and then start range and get first table but it gives me error.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
seif
  • 11
  • 2
  • 2
    what is the error that you are getting? and at what line does it appear – Joeri E Sep 11 '20 at 07:14
  • System.NullReferenceException: 'Object reference not set to an instance of an object.' table was null. – seif Sep 11 '20 at 07:21
  • Table table = doc.MainDocumentPart.Document.Elements().First();
    – seif Sep 11 '20 at 07:21
  • Hmm that indicates that its not finding an Table element. Could you check to ensure that both Document is correctly populated (not null) and elements have a collection of objects? – Spook Kruger Sep 11 '20 at 07:38

1 Answers1

0

try the following code to select the first table in your document

word.Table tbl = doc.Range(ref doc.Content.Start, ref doc.Content.End).Tables[1];
Joeri E
  • 111
  • 9