使用OleDbCommand时,指定的转换无效

它如何与Excel的工作

decimal LTLPrice = Decimal.Parse(sheet.get_Range("H27").Value.ToString()); decimal mathLTLPrice = Math.Round(LTLPrice, 2); sheet.get_Range("C29").Value = SumToTextFormatProvider.SumToText(mathLTLPrice, "Lt", "ct"); 

如何在我的想象中与OleDb

 myCommand = new OleDbCommand("SELECT * FROM [Sheet1$H27:H27]", MyConnection); myReader = myCommand.ExecuteReader(); while (myReader.Read()) { decimal LTLPrice = Decimal.Parse(myReader.GetString(0)); decimal mathLTLPrice = Math.Round(LTLPrice, 2); myCommand = new OleDbCommand("UPDATE [Sheet1$C29:C29] SET F1='" + SumToTextFormatProvider.SumToText(mathLTLPrice, "Lt", "ct") + "'", MyConnection); myCommand.ExecuteNonQuery(); } myReader.Close(); 

它是如何

 System.InvalidCastException: Specified cast is not valid. at System.Data.OleDb.ColumnBinding.ValueString() at System.Data.OleDb.OleDbDataReader.GetString(Int32 ordinal) at Trains.invoiceForm.invoiceGenerateXls_Click(Object sender, EventArgs e) in D:\Users\Nullified\Documents\Visual Studio 2010\Projects\Trains\Trains\invoiceForm.cs:line 592 

错误在这一行

 decimal LTLPrice = Decimal.Parse(myReader.GetString(0)); 

我曾尝试GetInt32 / GetDecimal但没有结果。 🙁

更新

与GetDouble我没有错误,但myReader返回我0,然后在Excel中它是“3,49”

我有类似的问题,这里是我的修补程序适用于您的问题:

  decimal LTLPrice = Convert.ToDecimal(myReader.GetValue(0).ToString()); 

通过攫取“价值”,你不必处理你正在拉的东西的具体细节,直到你尝试着去做。

当然,我的问题与你的只是有点不同,因为我不得不将所有东西都转换成string。 不过,这种方法应该仍然适用于你,因为Convert.ToDecimal将在string上工作,当然这个值是可以转换的。

你可以添加这个代码

 if(myReader.GetString(0) != null) { decimal LTLPrice = Decimal.Parse(myReader.GetString(0).Replace(",",".").Trim()); } 

发现问题,我通过oledb存储数字作为文本在Excel中,尽pipe事实上,如果我们在Excel中打开xls文件,我们仍然可以阅读,并且excel计算一切正常,oledb不能从Excel中得到正确的双值如果它是从存储为文本的数字计算。 现在只剩下要find如何在c#中存储双精度数字,问题将得到解决。