C# Excel匯入資料到資料庫
阿新 • • 發佈:2019-01-07
//專案中用到的一個小例子,拿出來和大家分享 ,需要引用
using System.IO;
using System.Data.OleDb;
/// <summary>
/// Excel資料匯入Datable/// </summary>
/// <param name="fileUrl"></param>
/// <param name="table"></param>
/// <returns></returns>
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();
}
}
/// <summary>
/// 從System.Data.DataTable匯入資料到資料庫
/// </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["姓名"].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);