//项目中用到的一个小例子,拿出来和大家分享 ,需要引用
using System.IO;
using System.Data.OleDb;
///
/// Excel数据导入Datable
///
///
///
///
public DataTable GetExcelDatatable(string fileUrl, string table)
{
//office2007之前 仅支持.xls
//const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
//支持.xls和.xlsx,即包括office2010等版本的 HDR=Yes代表第一行是标题,不是数据;
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;
//建立连接
OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
try
{
//打开连接
if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
{
conn.Open();
}
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//获取Excel的第一个Sheet名称
string sheetName = schemaTable.Rows[0]["table_name"].ToString().Trim();
//查询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();
}
}
///
/// 从System.Data.DataTable导入数据到数据库
///
///
///
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["姓名"].ToString().Trim();
sTalent.WORKFIELD = dr["工作领域"].ToString().Trim();
sTalent.TYPE = dr["类型"].ToString().Trim();
sTalent.TEL = dr["电话"].ToString().Trim();
qq = dr["QQ"].ToString().Trim();
sTalent.EMAIL = dr["Email"].ToString().Trim();
sTalent.ADDRESS = dr["住址"].ToString().Trim();
sTalent.INFO = dr["人才简介"].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, "人才信息");
bool flag = InsetData(dt);