简体   繁体   中英

Importing data from Excel using C#

I am new to the C# platform. I have made the application for importing Excel data in which I have showed the two text fields. 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.

But there is a problem when I entered the invalid sheet name then application crashed and because of the 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); .

Add a try/catch block - Example

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. 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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