简体   繁体   English

使用C#从Excel导入数据

[英]Importing data from Excel using C#

I am new to the C# platform. 我是C#平台的新手。 I have made the application for importing Excel data in which I have showed the two text fields. 我已经制作了导入Excel数据的应用程序,其中显示了两个文本字段。 The first takes path of Excel file, the second takes sheet name, and when I pressed the load button then it imports the data from Excel. 第一个采用Excel文件的路径,第二个采用工作表名称,当我按下加载按钮时,它将从Excel导入数据。

But there is a problem when I entered the invalid sheet name then application crashed and because of the system.Data.OleDb.OleDbException . 但是,当我输入无效的工作表名称时,由于system.Data.OleDb.OleDbException导致应用程序崩溃,这是一个问题。 The only thing I want to display the message `please enter the correct sheet number' on entering invalid sheet name. 输入无效的工作表名称时,我唯一想显示的消息是“请输入正确的工作表编号”。

Here is the code: 这是代码:

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;

When I entered the invalid sheet name then it creates the exception on the line myDataAdapter.Fill(dt); 当我输入无效的工作表名称时,它将在行myDataAdapter.Fill(dt);上创建异常myDataAdapter.Fill(dt); .

Add a try/catch block - Example 添加一个try / catch块- 示例

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

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

You can use the OleDbSchemaTable method to retrieve the sheet names in an excel file. 您可以使用OleDbSchemaTable方法在excel文件中检索工作表名称。 You can then check to see if the sheet name exists as follows: (I converted this from a VB function that is also included in case the conversion is incorrect) 然后,您可以检查表名是否存在,如下所示:(我是从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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM