使用C#从Excel导入数据

时间:2014-12-05 14:39:32

标签: c# oledbdataadapter

我是C#平台的新手。我已经创建了导入Excel数据的应用程序,其中我显示了两个文本字段。第一个采用Excel文件的路径,第二个采用工作表名称,当我按下加载按钮时,它从Excel导入数据。

但是当我输入无效的工作表名称然后应用程序崩溃并因为system.Data.OleDb.OleDbException时出现问题。我只想在输入无效的工作表名称时显示消息“请输入正确的工作表编号”。

以下是代码:

string PathConn = "Provider =Microsoft.Jet.OLEDB.4.0;Data Source=" + opentextfeild.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select email from [" + loadtextfeild.Text + "$] where email like '%@%'     ", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
displayviewgrid.DataSource = dt;

当我输入无效的工作表名称时,它会在行myDataAdapter.Fill(dt);上创建例外。

2 个答案:

答案 0 :(得分:1)

添加try / catch块 - Example

try
{
using (var myObject = new MyClass())
{
  // something here...

}
catch(Exception ex)
{
   // Handle exception
}

答案 1 :(得分:1)

您可以使用OleDbSchemaTable方法检索Excel文件中的工作表名称。然后,您可以检查工作表名称是否存在,如下所示:(我从VB函数转换它,如果转换不正确,也包括在内)

private static bool IsValidExcelWorksheetName(OleDbConnection m_connexcel, string Filepath, string SheetName)
{
    try {
        DataTable ExcelSheets = m_connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] {
            null,
            null,
            null,
            "TABLE"
        });
        foreach (DataRow Row in ExcelSheets.Rows) {
            if (Row.Item("TABLE_NAME") == SheetName)
                return true;
        }
        return false;
    } catch (Exception ex) {
        throw new Exception(ex.Message);
    }
}

<强> VB

Private Shared Function IsValidExcelWorksheetName(ByVal m_connexcel As OleDbConnection, _
                                                  ByVal Filepath As String, _
                                                  ByVal SheetName As String) As Boolean
    Try
        Dim ExcelSheets As DataTable = m_connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
        For Each Row As DataRow In ExcelSheets.Rows
            If Row.Item("TABLE_NAME") = SheetName Then Return True
        Next
        Return False
    Catch ex As Exception
        Throw New Exception(ex.Message)
    End Try
End Function