Use a zero (0) in a data field when the measured result is zero. Use 3 hyphens (---) to indicate there is no result available. Do not leave a data field blank

Hi Team,

I need a code to Use a zero (0) in a data field when the measured result is zero in cell. Use 3 hyphens (—) to indicate there is blank cell in a table. Do not leave a data field blank.

Thanks and Regards,
Harish G

@HarishGali If you are using mail merge, you can implement this using IFieldMergingCallback. For example see the following simple code and documents:

DataTable dt = new DataTable("MyTable");
dt.Columns.Add("Name");
dt.Columns.Add("Value", typeof(int));
dt.Rows.Add("NotZeroValue", 10);
dt.Rows.Add("ZeroValue", 0);
dt.Rows.Add("AnotherZeroValue", 0);
dt.Rows.Add("AnotherNotZeroValue", 10);

Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.FieldMergingCallback = new InsertHyphenMergingCallback();
doc.MailMerge.ExecuteWithRegions(dt);
doc.Save(@"C:\Temp\out.docx");
private class InsertHyphenMergingCallback : IFieldMergingCallback
{
    public void FieldMerging(FieldMergingArgs args)
    {
        if (args.FieldName == "Value" && (int)args.FieldValue == 0)
        {
            args.Text = "---";
            args.FieldValue = "";
        }
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing
    }
}

in.docx (12.8 KB)
out.docx (10.1 KB)

for already existing tables in document if the cell text is zero then replace with (0) and if the cell is empty or blank then add —.
this is the requirement

@HarishGali Could you please attach your input and expected output documents here for our reference? We will check the documents and provide you more information.

code has to check every table in document and every cell in table and replace zero with (0) and empty cell with — as shown in attached documentsoutputExpected.docx (15.6 KB)
input.docx (15.8 KB)

@HarishGali You can achieve this using code like the following:

Document doc = new Document(@"C:\Temp\input.docx");

// Get cells from the document.
NodeCollection cells = doc.GetChildNodes(NodeType.Cell, true);
foreach (Cell c in cells)
{
    // Put "---" into empty cells.
    if (string.IsNullOrEmpty(c.ToString(SaveFormat.Text).Trim()))
        c.FirstParagraph.AppendChild(new Run(doc, "---"));
}

doc.Save(@"C:\temp\out.docx");

also need code to replace the “zero” with “(0)”

@HarishGali You can easily achieve this using Find/Replace functionality. For example see the following code:

Document doc = new Document(@"C:\Temp\input.docx");
doc.FirstSection.Body.Tables[0].Range.Replace("zero", "(0)");
doc.Save(@"C:\Temp\out.docx");
``