Home » excel » How can i change the text format of a Excel Cell using C#?

How can i change the text format of a Excel Cell using C#?

Posted by: admin March 9, 2020 Leave a comment

Questions:

I am currently writing an application (C#) to generate reports in a excel file, based on other reports.

The problem is that, once get an number from a certain sheet, and copy to another one, the destination cell is not formated correctly, and the number does no display correctly.

E.g : 
Number from source : 14.34 
Number on destination : 14.345661

How do i format the destination cell to force the number formating to be the same as the source cell.

Thanks !

How to&Answers:

The format of a given cell/range in excel can be set via code.

public void SetCustomFormat(string format, int r, int c)
{
    ((Excel.Range)xlWks.Cells[r, c]).NumberFormat = format;
}

In your specific case, I believe you would need to use the format “#.00” or “#.##”

Answer:

Here’s a snippet from some code I’ve got in use, to show you the general pattern for formatting cells. Obviously, there are some variables declared, but it should show you what you need.

sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Font.Bold = true;
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Interior.Color = Color.Silver.ToArgb();
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
sheet.get_Range("A" + CompetencyStartRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);

That first line, assuming CurrentRowIndex = 1 and ColPrefix = “B”, replacing the variables with the resulting values would translate into

sheet.get_Range("A1", "B1").Font.Bold = true;

At any rate, you want to set the numberformat. (Coming..)

sheet.Cells[Row, Column].NumberFormat = "0.00"