Below code snippet is to import data from Excel to a Dataset
string strExcelFilename = txtExcelFilename.Text;
//Use Microsoft JET OLEDB Provider
string strConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + strExcelFilename + ";" + @"Extended Properties=" + Convert.ToChar(34).ToString() + @"Excel 8.0;HDR=YES" + Convert.ToChar(34).ToString();
OleDbConnection objCon = new OleDbConnection(strConnectionString);
try
{
objCon.Open();
//By default spreadsheet first sheet will be sheet1 unless it is renamed
string strExcelSheetName = "ExcelSheetName";
string strSQL = "SELECT * FROM [" + strExcelSheetName + "$" + "]";
OleDbDataAdapter objoleAdapter = new OleDbDataAdapter(strSQL, objCon);
objoleAdapter.Fill(ds, "tblImportedData");
SqlBulkCopy bulkCopy = new SqlBulkCopy("Server=ServerName;Database=test;Trusted_Connection=True;",SqlBulkCopyOptions.TableLock); bulkCopy.DestinationTableName = "Destination Table Name";
bulkCopy.WriteToServer(ds.Tables[0]);
}
catch (Exception ex)
{
Response.Write(ex.Message);
return;
}
string strExcelFilename = txtExcelFilename.Text;
//Use Microsoft JET OLEDB Provider
string strConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + strExcelFilename + ";" + @"Extended Properties=" + Convert.ToChar(34).ToString() + @"Excel 8.0;HDR=YES" + Convert.ToChar(34).ToString();
OleDbConnection objCon = new OleDbConnection(strConnectionString);
try
{
objCon.Open();
//By default spreadsheet first sheet will be sheet1 unless it is renamed
string strExcelSheetName = "ExcelSheetName";
string strSQL = "SELECT * FROM [" + strExcelSheetName + "$" + "]";
OleDbDataAdapter objoleAdapter = new OleDbDataAdapter(strSQL, objCon);
objoleAdapter.Fill(ds, "tblImportedData");
SqlBulkCopy bulkCopy = new SqlBulkCopy("Server=ServerName;Database=test;Trusted_Connection=True;",SqlBulkCopyOptions.TableLock); bulkCopy.DestinationTableName = "Destination Table Name";
bulkCopy.WriteToServer(ds.Tables[0]);
}
catch (Exception ex)
{
Response.Write(ex.Message);
return;
}
No comments:
Post a Comment