I have a simple formula in a number of cells and I'm trying to get the result of that formula into a variable in my program. My inital code was:
var ECC = ws.Cells["B14"].Value; decimal ECP = Convert.ToDecimal(ECC);
but this got me an error "System.InvalidCastException: 'Unable to cast object of type 'OfficeOpenXml.ExcelErrorValue' to type 'System.IConvertible'.'" I tried calculating and adding a toString, making my code:
ws.Cells["B14"].Calculate(); decimal ECP = Convert.ToDecimal(ws.Cells["B14"].Value.ToString());
This got me a different error: "System.FormatException: 'Input string was not in a correct format.'" on the second line.
The result of the formula will always be a decimal and it's important that I get it into a decimal variable because I'm putting that value into a SQL database. How can I do this error-free?
This works in one my apps:
var pressure = informationWorkSheet.Cells[30, 3];
Cast it to a Decimal:
Decimal pressureDecimal = (Decimal) pressure;
Or parse it:
Decimal.Parse(pressure.ToString());
Try this approach with decimal.TryParse
. Works as expected in my sample application. Tested with values: 3,2 / 3.2 / 5
string ECC = ws.Cells["B14"].Value.ToString();
bool isDecimal = decimal.TryParse(ECC, out decimal result);
if (isDecimal)
{
decimal ECP = result;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.