How to learn Excel Cell formatting

Is it possible to calculate the format of an Excel cell, I know that .NumberFormat exists, but it returns formatting, but not type ... basically I need to know if it is normal, then it should return custom, and if it should return currency, it should return currency or any other type of data Please help me

+3
source share
3 answers

Under the hood, Excel stores values ​​in a special way (most data types actually double), and this makes it difficult to detect cell formats without the help of Excel.

Therefore, I recommend that you use the built-in Excel function CELL, rather than querying data types yourself:

enter image description here

private void button1_Click(object sender, EventArgs e) 
{
    //C1 is a cell I use to evaluate the Format of Cells A1 thru to A7
    using (var rnEvaluate = xlApp.Range["C1:C1"].WithComCleanup())
    {
        for (int i = 1; i < 8; i++)
        {
            rnEvaluate.Resource.Value2 = "=CELL(\"format\",A" + i.ToString() + ")";
            string cellFormat = GetExcelCellFormat(rnEvaluate.Resource.Value2);
            System.Diagnostics.Debug.Write(cellFormat);
        }
    } 
}

private string GetExcelCellFormat(string cellFormat = "G") 
{
    switch (cellFormat.Substring(0, 1))
    {
        case "F" :
            return "Number";
            break;
        case "C":
            return "Currency";
            break;
        case "D":
            return "Date";
            break;
        default :
            return "General";
            break;
    } 
}

ps .WithComCleanup() , VSTO Contrib

+3

, xslx (Open XML excel), xlslx (xlsx - zip ) xl\worksheets\sheet {?}. xml .

, .

0

NumberFormat Excel , Microsoft. , .

, ( Excel 2010):

  • "0.00" -
  • "$ #, ## 0.00" -
  • "_ ($ * #, ## 0.00 _); _ ($ * (#, ## 0.00); _ ($ *" "-" "??); (@_)" -
  • "m/d/yyyy" -
  • "[$ - F800] dddd, mmmm dd, yyyy" -
  • "[$ - F400] h: mm: ss AM/PM" -
  • "0.00%" -
  • "#?/?" -
  • "0.00E + 00" - Scientific
  • "@" -
  • "" -

, .


EDIT:
, - , Excel ( , NumberFormat):

string fileName = @"c:\Book1.xlsx";
Application app = new Application();
Workbook wb = app.Workbooks.Open(fileName,
   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
   Type.Missing, Type.Missing);
Worksheet sheet = wb.Sheets[1];  //Change to the sheet you care about (1 based index)
var cell = sheet.Cells[1, 1];    //Change to the cell you care about (1 based index)
string cellNumberFormat = cell.NumberFormat; //Number format of cell to compare against known values

interop .

0
source

Source: https://habr.com/ru/post/1744262/


All Articles