A small example used in the project, take out and share with you, need to quote
Using System.IO;
Using System.Data.OleDb;
<summary>///Excel data import datable
</summary>
<param name= "FileUrl" ></param>
<param name= "Table" ></param>
<returns></returns>
Public DataTable getexceldatatable (string fileUrl, String table)
{
Office2007 only supports. xls before
Const string Cmdtext = "Provider=Microsoft.Jet.OLEDB.4.0;Data source={0};" Extended properties= ' Excel 8.0;imex=1 ';
Support. xls and. xlsx, that is, including office2010 and other versions of the Hdr=yes represent the first line is the title, not the data;
Const string Cmdtext = "Provider=Microsoft.Jet.OLEDB.4.0;Data source={0};" Extended properties=\ "Excel 8.0; Hdr=yes; Imex=1;\ "";
System.Data.DataTable dt = null;
Establish a connection
OleDbConnection conn = new OleDbConnection (string. Format (Cmdtext, FILEURL));
Try
{
Open connection
IF (Conn. State = = Connectionstate.broken | | Conn. state = = connectionstate.closed)
{
Conn. Open ();
}
System.Data.DataTable schematable = conn. GetOleDbSchemaTable (OleDbSchemaGuid.Tables, NULL);
Get the first sheet name for Excel
String sheetname = schematable.rows[0]["table_name"]. ToString (). Trim ();
Querying the data in sheet
String strSQL = "SELECT * FROM [" + SheetName + "a:h]";
OleDbDataAdapter da = new OleDbDataAdapter (strSQL, conn);
DataSet ds = new DataSet ();
Da. Fill (ds, table);
DT = ds. Tables[0];
return DT;
}
catch (Exception exc)
{
Throw exc;
}
Finally
{
Conn. Close ();
Conn. Dispose ();
}
}
<summary>
Importing data from System.Data.DataTable to a database
</summary>
<param name= "DT" ></param>
<returns></returns>
public bool Insetdata (System.Data.DataTable DT)
{
BOOL flag = FALSE; string QQ = "";
foreach (DataRow dr in Dt. Rows)
{
Stalent.id = Guid.NewGuid (). ToString ();
Stalent.name = dr["Name". ToString (). Trim ();
Stalent.workfield = dr["Work area"]. ToString (). Trim ();
Stalent.type = dr["type"]. ToString (). Trim ();
Stalent.tel = dr["Phone"]. ToString (). Trim ();
QQ = dr["QQ"]. ToString (). Trim ();
Stalent.email = dr["EMAIL"]. ToString (). Trim ();
Stalent.address = dr["Address"]. ToString (). Trim ();
Stalent.info = dr["Talent profile"]. ToString (). Trim ();
Stalent.createdate = DateTime.Now;
STALENT.BATCH.ADD (Stalent.getinsertcommand ());
}
Try
{
Flag = STalent.DataManager.Execute (STalent.Batch.GetBatch ());
}
catch (Exception ex)
{
}
return flag;
}
DataTable dt = getexceldatatable (path, "talent information");
BOOL flag = insetdata (DT);