Excel导入数据库_Excel2Sql

        //Excel转Sql方法
public static DataTable Excel2DataTable(string filePath, string sheetName)
{
DataTable dt = null;
//HDR=Yes:第一行是列名
//IMEX=1:把数据作为text 类型
string conStr = string.Format("Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';", filePath);
string strSql = string.Format("select * from [{0}$]", sheetName);
OleDbConnection con = new OleDbConnection(conStr);
OleDbDataAdapter oda = new OleDbDataAdapter(strSql, conStr);
try
{
dt = new DataTable();
oda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
oda.Dispose();
con.Close();
con.Dispose();
}
}
//DataTable2Sql
string conString = "server=.;database=Test;uid=sa;pwd=1112";
//调用Excel转Sql方法
DataTable dt = Excel2DataTable(@"C:\Users\Administrator\Desktop\朱家埭.xlsx", "1-朱炳南");
//创建批量DataTable导入Sql
SqlBulkCopy copy = new SqlBulkCopy(conString, SqlBulkCopyOptions.UseInternalTransaction);
//指定数据库表名
copy.DestinationTableName = "Excel";
//写入Sql
copy.WriteToServer(dt);

 

你可能感兴趣的:(Excel)