Excel中的資料匯入到 DB 中常用的方法是 先把Excel中资料加入到临时表Datatable中,然后循环写入DB
Excel2003 与Excel2007以上版本的 驱动不同
Excel2003 是:
Provider=Microsoft.Jet.OLEDB.4.0;" + " Data Source=" + fileName + ";" + " Extended Properties='Excel 8.0; HDR=NO; IMEX=1
Excel2007 以上为:
Provider = Microsoft.ACE.OLEDB.12.0 ; " + " Data Source =" + fileName + ";" + " Extended Properties=Excel 12.0;HDR=NO; IMEX=1
以下为把Excel中的资料到导人Dataset中:
/// <summary>
/// 从Excel文件导入DataSet
/// HDR=Yes 表示第一行是表头,没有数据,读取时忽略第一行。设置为 No 时则从第一行读取
/// IMEX=1 表示告诉OleDb驱动,所有数据将作为字符串读取(numbers,dates等)
/// 注意:有时候因为ISAM驱动没有安装,设置HDR和IMEX会出异常。去掉即可。
/// </summary>
/// <param name="fileName">Excel文件路径</param>
/// <param name="sheetName">Excel頁簽名稱 :Sheet</param>
/// <param name="firstRowIsHeader">第一行是否是表头</param>
/// <returns></returns>
public static DataSet GetDataSetFromExcel(string fileName, string fileExtension,string sheetName = "", bool firstRowIsHeader = true)
{
if (!System.IO.File.Exists(fileName))
throw new ArgumentException("Excel文件不存在!");
DataSet ds = new DataSet();
var strConn="";
if (fileExtension == ".xls")
{
strConn = " Provider=Microsoft.Jet.OLEDB.4.0;" + " Data Source=" + fileName + ";" + " Extended Properties='Excel 8.0; HDR=NO; IMEX=1'";
}
else
{
strConn = "Provider = Microsoft.ACE.OLEDB.12.0 ; " + " Data Source =" + fileName + ";" + " Extended Properties=Excel 12.0;HDR=NO; IMEX=1'";
}
//strConn = string.Format(strConn, fileName);
strConn = string.Format(strConn);
using (var conn = new OleDbConnection(strConn))
{
try
{
conn.Open();
}
catch
{
MessageBox.Show("請確定已安裝Excel軟件且未打開需要匯入的Excel模板!");
}
System.Data.DataTable exceldt = null;
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = conn.CreateCommand();
if (string.IsNullOrEmpty(sheetName))
{
exceldt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow row in exceldt.Rows)
{
string sheet = row["TABLE_NAME"].ToString();
if (sheet == "Test$") //Excel页签名称,取指定页签下的Excel资料
{
string strsql = "select * from [{0}]";
strsql = string.Format(strsql, sheet);
da.SelectCommand.CommandText = strsql;
da.Fill(ds, sheet);
}
}
}
else
{
string strsql = "select * from [{0}]";
strsql = string.Format(strsql, sheetName);
da.SelectCommand.CommandText = strsql;
da.Fill(ds, sheetName);
}
conn.Close();
}
return ds;
}