如何在C#中检查input(xls)文件的内容types?

我必须在C#中读取.xlsx文件。 我正在做如下。 但我的行可以有string或双。

 Input Excel Test file 1 v1 c1 -3.99 

码:

 private void button1_Click(object sender, EventArgs e) { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Excel.Range range; string str; int rCnt = 0; int cCnt = 0; xlApp = new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); range = xlWorkSheet.UsedRange; for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++) { for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++) { str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ; MessageBox.Show(str); } } xlWorkBook.Close(true, null, null); xlApp.Quit(); } 

现在我在下面的语句中出现错误:如何检查行对象是double还是string?

 string str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2; 

 object value = x.Value2; string str = value as string; if (str != null) { // I am string } double? d = value as double?; if (d != null) { // d.Value is double } 

你可以尝试parsing成double如果失败使用string:

 if(!double.TryParse(input, out result)) resultString = input.ToString(); 

那么你可以检查resultString.IsNullOrEmpty是否使用双重结果或stringresultString。