如何在C#中检查输入(xls)文件的内容类型?

时间:2012-03-20 11:55:55

标签: c# .net excel vsto

我必须在C#中读取.xlsx文件。我这样做。但我的行可以有字符串或双精度。

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();
}

现在我在以下语句中收到错误:如何检查行对象是双精度还是字符串?

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

2 个答案:

答案 0 :(得分:1)

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
}

答案 1 :(得分:-1)

如果失败则可以尝试将其解析为double:

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

然后你可以检查resultString.IsNullOrEmpty是否使用double结果或字符串resultString。