0

Cells of Excel spreadsheet are read using Microsoft.Office.Interop.Excel object. I need to find out formatting for number values and apply accordingly. For instance I have 19.0000 value but when it is read Value2 will be "19" however I need to keep it "19.0000"

Excel.Range sheetRange = xlWorksheet.Range["A1", lastCell];
var cell = sheetRange.Cells[row, col];
cell.Value2 == "19";

There is a NumberFormat property that returns formatting string like "0.0000" that I could use, but I can't find out how to check if cell value is a number.

Maxim
  • 4,152
  • 8
  • 50
  • 77

2 Answers2

0

a bit of a hacky way around it is to add an apostrophe at the beginning - excel wont try to format it then

for instance var value = 19.0000; cell.value = "'" + value;

Phyushin
  • 1
  • 2
0

I use this function for that purpose:

    public static bool IsValidDecimalNumber(this string s)
    {
        if (string.IsNullOrWhiteSpace(s)) return false; //blank/null strings aren't valid decimal numbers
        return !s.Any(c => !(char.IsDigit(c) || c == '.')) && !(s.Count(c => c == '.') > 1);
    }

Edit: to elaborate, it returns false if it's blank/null, then it returns false if any digits aren't a number or a decimal point, and it returns false if there's more than one decimal point. Otherwise, it returns true.

Yushatak
  • 741
  • 1
  • 5
  • 15