问题
I am trying to get cells from excel into csharp but not sure what's the best variable type to read it into.
If I make the variable a string and the cell value is a double I get a parse error. If I make the variable double then when the cell is a string it wont work.
Here's the code I am 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());
}
回答1:
Make it an object, then find out the right type after you have gotten the value out of the cell.
I don't know about VSTO, but in the Excel Interop assembly, there were a Value2
and a Text property which both returned object, and could be casted through polymorphism to the correct type. Doesn't VSTO provide those?
回答2:
You could just call ToString() on the object and then do double.TryParse() to see if the value is numeric or text
回答3:
Simply
double x = (double)Globals.Sheet1.Cells[7, 7].Value;
will get you the double value or throw an exception (no need to catch it, it will be displayed properly in a dialog box in Excel if nothing catches it upstream).
回答4:
I prefer to get the text value directly and do not want to deal with the underlying datatype for the most part. I get the text value as TravisWhidden comment mentioned, here is my VSTO C# code to achieve a read from a cell and return a text value regardless of the base object.
This my extension method which works off of 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;
}
回答5:
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());
}
来源:https://stackoverflow.com/questions/4341785/how-to-best-fetch-a-cell-value-from-excel-using-vsto