Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

excel

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 !

like image 524
Marcello Grechi Lins Avatar asked May 23 '12 13:05

Marcello Grechi Lins


People also ask

How do I format text in an Excel cell?

Format Part of a Cell Select the cell you want to format. In the formula bar, select the text you want to format. Select the text formatting you want to use. Press Enter.


2 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 "#.##"

like image 80
Nevyn Avatar answered Oct 14 '22 23:10

Nevyn


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"
like image 42
David Avatar answered Oct 14 '22 22:10

David