What is the best way to get cell value from excel using VSTO?

I am trying to get cells from excel in csharp, but not sure if the best type of variable is to read it.

If I make the variable a string and the cell value is double, I get a parsing error. If I make a double variable, then when the cell is a row, it will not work.

Here is the code I'm running:

 try
 {
        string i = Globals.Sheet1.Cells[7, 7].Value;
        double num;
        if (i == null) return;

        if (double.TryParse(i, out num)) 
        {
              .
              .
              .
        }
}
catch (Exception e)
{
       MessageBox.Show(e.ToString());
}
+3
source share
5 answers

Make it an object, then find out the correct type after you get the value from the cell.

VSTO, Excel Interop Value2 Text, . VSTO ?

+4

ToString() , double.TryParse(), ,

0

double x = (double)Globals.Sheet1.Cells[7, 7].Value;

( , Excel, ).

0

I prefer to get the text value directly and don't want to deal with the underlying data type for the most part. I get a text value as mentioned by TravisWhidden comment, here is my VSTO C # code to get a reading from a cell and return a text value regardless of the underlying object.

This is my extension method that works on the worksheet page:

public static string CellGetStringValue(this WorksheetBase theSheet, int row, int column)
{
    var result = string.Empty;

    if (theSheet != null)
    {
        var rng = theSheet.Cells[row, column] as Excel.Range;

        if (rng != null)
            result = (string) rng.Text;
    }

    return result;
}
0
source
 try
 {

    dynamic mycell = Globals.Sheet1.Cells[7, 7];
    double num;
    if (mycell.Value == null) return; //you can use mycell.Text too.

    if (double.TryParse(mycell.Text, out num)) 
    {
          .
          .
          .
    }
}
catch (Exception e)
{
       MessageBox.Show(e.ToString());
}
0
source

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


All Articles