private void ImportExcel(string strFilePath) { if (!File.Exists(strFilePath)) ; String strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strFilePath + ";" + "Extended Properties='Excel 8.0;HDR=Yes'"; OleDbConnection connExcel = new OleDbConnection(strExcelConn); OleDbCommand cmdExcel = new OleDbCommand(); try { cmdExcel.Connection = connExcel; //Check if the Sheet Exists connExcel.Open(); DataTable dtExcelSchema; //Get the Schema of the WorkBook dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); connExcel.Close(); //Read Data from Sheet1 connExcel.Open(); OleDbDataAdapter da = new OleDbDataAdapter(); DataSet ds = new DataSet(); string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString(); cmdExcel.CommandText = "SELECT * From [" + SheetName + "]"; da.SelectCommand = cmdExcel; da.Fill(ds); for (int i = 0; i <= ds.Tables[0].Rows.Count; i++) { string name = ds.Tables[0].Rows[i].ToString(); } connExcel.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "ImportExcel"); } finally { cmdExcel.Dispose(); connExcel.Dispose(); } }
Column Index
int columnIndex =1; // the column index of the table which you want to read string name = ds.Tables[0].Rows[i][columnIndex].ToString();
Column Name
string columnName = "Column1"; // name of the column in the DataTable string name = ds.Tables[0].Rows[i][columnName].ToString();
ds.Tables[0].Rows[i][columnNameorIndex].ToString();
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)