New to Telerik Document Processing? Download free 30-day trial

Change Cells Content

Product Version Product Author
2020 R3 RadWordsProcessing Dimitar Karamfilov

Description

You have a template that contains a table and you need to get this particular table and populate its cells using WordsProcessing.

Solution

To get all tables you can use the EnumerateChildrenOfType method, then you can iterate the table and populate the cells with data.

Iterate table Cells and add content

var provider = new DocxFormatProvider(); 
var document = provider.Import(File.ReadAllBytes("template.docx")); 
 
var tables = document.EnumerateChildrenOfType<Table>().ToList(); 
 
var myTable = tables[1]; 
 
foreach (var row in myTable.Rows) 
{ 
    foreach (var cell in row.Cells) 
    { 
        if (cell.Blocks.Count <= 0) 
        { 
            var paragraph = cell.Blocks.AddParagraph(); 
            var run = paragraph.Inlines.AddRun(); 
            run.Text = "Test"; 
        } 
        else 
        { 
            var paragraph = cell.Blocks[0] as Paragraph; 
            if (paragraph != null) 
            { 
                if (paragraph.Inlines.Count > 0) 
                { 
                    paragraph.Inlines.Clear(); 
                } 
                var run = paragraph.Inlines.AddRun(); 
                run.Text = "Test"; 
            } 
        } 
    } 
} 
 
var bytes = provider.Export(document); 
File.WriteAllBytes("result.docx", bytes); 
In this article