ASPOSE WORD Remove a Row on a table

Hi,

I have a Document [kind of a template]. During runtime, based on a certain condition I need to remove a row on a table.

Example: As shown below, I need to remove row #1 if the DBField1 value is FAIL. Is it possible to accomplish using ASPOSE? If so, Can you please post a sample code?

Test Result Comments
Test 1 Pass show this row if <<DBField1>> = PASS
Test 2 Fail show this row if <<DBField2>> = FAIL If Correction Method is ‘Recharacterized as catch-up’ show “Contributions recharacterized as catch-up. Test satisfied.”

Hi Rob,

Thanks for your inquiry. Yes, you can achieve your requirements by using Aspose.Words. Please use the following code snippet to remove the row from table, you need to modify the If condition according to your requirement. Hope this helps you. Please let us know if you have any more queries.

// Open document
Document doc = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField("DBField1", true, false);
if (condition...) // If DBField1 is fail
{
    Row row = (Row) builder.CurrentNode.GetAncestor(NodeType.Row);
    if (row != null)
        row.Remove();
}

Hi Tahir,

Thank You for your reply. But, the solution i am looking for is kind of Find and Replace or Remove the row based on the DBField Value. Please find the attachment and let me know how to accomplish the task. And one more question is, is it possible to open the source file always in readonly mode so other users can acess it at a given point of time. I need the solution ASAP.

-Rob.

Hi Rob,

Thanks for your inquiry.

robert.owens:
But, the solution i am looking for is kind of Find and Replace or Remove the row based on the DBField Value. Please find the attachment and let me know how to accomplish the task.

The article ‘Find and Replace Overview’ sounds like exactly what you want. Please also check following documentaion link for your kind refernce.
https://docs.aspose.com/words/java/find-and-replace/

Please use the following code snippet to find the text ‘REMOVE_ROW’ and remove the Row. Hope this helps you.

Document doc = new Document(MyDir + "Test.docx");
Regex regex = new Regex("REMOVE_ROW", RegexOptions.IgnoreCase);
doc.Range.Replace(regex, new ReplaceEvaluatorFindAndDeleteRow(), true);
// Save the output document.
doc.Save(MyDir + "TestFile Out.doc");
private class ReplaceEvaluatorFindAndDeleteRow: IReplacingCallback
{
    ///
    /// This method is called by the Aspose.Words find and replace engine for each match.
    /// This method highlights the match string, even if it spans multiple runs.
    ///
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.MatchNode;
        // The first (and may be the only) run can contain text before the match,
        // in this case it is necessary to split the run.
        if (e.MatchOffset> 0)
            currentNode = SplitRun((Run) currentNode, e.MatchOffset);
        // This array is used to store all nodes of the match for further highlighting.
        ArrayList runs = new ArrayList();
        // Find all runs that contain parts of the match string.
        int remainingLength = e.Match.Value.Length;
        while ((remainingLength> 0) &&
            (currentNode != null) &&
            (currentNode.GetText().Length <= remainingLength))
        {
            runs.Add(currentNode);
            remainingLength = remainingLength - currentNode.GetText().Length;
            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do {
                currentNode = currentNode.NextSibling;
            }
            while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
        }
        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength> 0))
        {
            SplitRun((Run) currentNode, remainingLength);
            runs.Add(currentNode);
        }
        //// Now highlight all runs in the sequence.
        // foreach (Run run in runs)
        // run.Font.HighlightColor = Color.Cyan;
        Row row = (Row)((Run) runs[0]).GetAncestor(NodeType.Row);
        if (row != null)
            row.Remove();
        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.Skip;
    }
}
///
/// Splits text of the specified run into two runs.
/// Inserts the new run just after the specified run.
///
private static Run SplitRun(Run run, int position)
{
    Run afterRun = (Run) run.Clone(true);
    afterRun.Text = run.Text.Substring(position);
    run.Text = run.Text.Substring(0, position);
    run.ParentNode.InsertAfter(afterRun, run);
    return afterRun;
}

robert.owens:
And one more question is, is it possible to open the source file always in readonly mode so other users can acess it at a given point of time.

Once you have loaded your document into Aspose.Words DOM, other users can use this document. The Aspose.Words Document Object Model (DOM) is an in-memory representation of a Word document. The Aspose.Words DOM allows you to programmatically read, manipulate and modify content and formatting of a Word document. Please read the detail of let us know if you have any more queries.

Hi Tahir,

Thank You for the quick reply. I tried your code, I am having trouble with removing rows on a table.
Attached is the Template and the program file. Please look into this as soon as possible as our company have already bought aspose total license and we need to make this working in 2 days.

Regards,
Rob

Hi Rob,

Thanks for your inquiry. I have modified the code, please see the highlighted section in following code example. I have attached the output document with this post for your kind reference. Hope this helps you.

DataTable dt;
dt = new DataTable();
dt.Columns.Add("ADPTESTINGRESULTS", typeof(string));
dt.Columns.Add("ADPCORRECTIONMETHOD", typeof(string));
dt.Columns.Add("ACPTESTINGRESULTS", typeof(string));
DataRow dr = dt.NewRow();
dr["ADPTESTINGRESULTS"] = "Pass";
dr["ADPCORRECTIONMETHOD"] = "";
dr["ACPTESTINGRESULTS"] = null;
dt.Rows.Add(dr);
// Open document
Document doc = new Document(MyDir + "temp.docx");
string content = doc.Range.Text;
Regex regex = new Regex("<>", RegexOptions.IgnoreCase);
ReplaceOrSupress obj = new ReplaceOrSupress(dt);
doc.Range.Replace(regex, obj, true);
foreach(Row row in obj.nodes)
{
    row.Remove();
}
doc.Save(MyDir + "out.docx");
public class ReplaceOrSupress: IReplacingCallback
{
    private DataTable dt;
    public ArrayList nodes = new ArrayList();
    public ReplaceOrSupress(DataTable temp)
    {
        dt = temp.Copy();
    }
    ///
    /// This method is called by the Aspose.Words find and replace engine for each match.
    /// This method removes the table row based on the value of the Variable.
    ///
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.MatchNode;
        string FinalValue = GetMailMergeValue(e.Match.Value, dt); // This Method fetches the value from the database
        if (e.MatchOffset> 0)
            currentNode = SplitRun((Run) currentNode, e.MatchOffset);
        // This array is used to store all nodes of the match for further highlighting.
        ArrayList runs = new ArrayList();
        // Find all runs that contain parts of the match string.
        int remainingLength = e.Match.Value.Length;
        while ((remainingLength> 0) &&
            (currentNode != null) &&
            (currentNode.GetText().Length <= remainingLength))
        {
            runs.Add(currentNode);
            remainingLength = remainingLength - currentNode.GetText().Length;
            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do {
                currentNode = currentNode.NextSibling;
            }
            while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
        }
        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength> 0))
        {
            SplitRun((Run) currentNode, remainingLength);
            runs.Add(currentNode);
        }
        if (FinalValue == "REMOVE_ROW")
        {
            Row row = (Row)((Run) runs[0]).GetAncestor(NodeType.Row);
            nodes.Add(row);
        }
        else
        {
            e.Replacement = FinalValue;
            return ReplaceAction.Replace;
        }
        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.Skip;
    }
}

Thanks Tahir. And one last thing, ASPOSE Regular expression engine can not handle new line breaks, right?

Hi Rob,

Thanks for your inquiry. Unfortunately, you cannot use special character in replacement and captured strings. “An exception is thrown if a captured or replacement string contain one or more special characters: paragraph break, cell break, section break, field start, field separator, field end, inline picture, drawing object, footnote.”

In future we will consider improving Replace method in order to support special characters. Your request has been linked to the appropriate issue (i.e. WORDSNET-1252) in our bug tracking system and you will be notified as soon as it is resolved.

We apologize for your inconvenience.

The issues you have found earlier (filed as WORDSNET-1252) have been fixed in this .NET update and this Java update.

This message was posted using Notification2Forum from Downloads module by aspose.notifier.
(21)