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 !
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.
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 "#.##"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With