主要问题
1,如何讲exel里面的一张张的表依次读出
2,如何批量导入数据
解决思路
1,excel里面各个表名被成为sheetName,由以下几句便可以获得:
DataTable sheetNames = conn.GetOleDbSchemaTable
(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
conn.Close();
al = sheetNames.Rows[0]["TABLE_NAME"].ToString();
当然,这里al只是取到了第一个的表明,其实可以用foreach语句依次取出所有的表明。
2,批量导入到指定的表
SqlBulkCopy 帮我解决了这个问题.
所有代码如下:
/// <summary>
///insertDAta 的摘要说明
/// </summary>
public class insertDAta
{
public insertDAta()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public string GetSourceTableName(string filepath)
{
string al = "";
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 3.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable sheetNames = conn.GetOleDbSchemaTable
(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
conn.Close();
al = sheetNames.Rows[0]["TABLE_NAME"].ToString();
return al;
}
public bool ITData(string sourceTable,string fullPath,string DestnationTable)
{
if (!File.Exists(fullPath))
{
return false;
}
else
{
string execelConnectionStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
using (OleDbConnection conn = new OleDbConnection(execelConnectionStr))
{
OleDbCommand cmd = new OleDbCommand("select * FROM [" + sourceTable + "]", conn);
conn.Open();
using (DbDataReader dr = cmd.ExecuteReader())
{
string sqlConnectionString =DB.SqlConString;
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = DestnationTable;
bulkCopy.WriteToServer(dr);
}
}
}
return true;
}
}
}