1. 程式人生 > >讀取Excel的記錄並導入SQL數據庫

讀取Excel的記錄並導入SQL數據庫

client click eve pri cep 時間 ger jpg exception

準備一下,近段時間,需要把Excel的數據導入數據庫中。

引用命名空間:

using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

你可以寫一個方法,是去讀取Excel文檔的方法,返回DataSet數據集:
技術分享

技術分享
private DataSet ImportExcelToDataSet(string virtualPath, string sqlQueryStatement)
    {
        string
excelConnectionString = DB.ExcelConnectionString(Server.MapPath(virtualPath)); OleDbConnection dc = new OleDbConnection(excelConnectionString); OleDbDataAdapter da = new OleDbDataAdapter(sqlQueryStatement, dc); DataSet ds = new DataSet(); da.Fill(ds); return
ds; }
Source Code


導入數據庫,在數據庫中,需要創建一個表來存儲Excel導入來的數據:
技術分享


接下來,你可以使作SqlBulkCopy的方法進行復制數據庫:

技術分享

技術分享
try
        {
            string cs = ConfigurationManager.ConnectionStrings["InsusSqlConnectionString"].ConnectionString;
            using (SqlConnection sqlConn = new SqlConnection(cs))
            {
                
string sqlQueryStatement = "SELECT [Material],[Plnt],[Level],[Item],[Component],[Object description] FROM [Sheet1$]"; string virtualPath = "~/App_Data/Book1.xlsx"; DataSet ds = ImportExcelToDataSet(virtualPath, sqlQueryStatement); DataTable dt = ds.Tables[0]; sqlConn.Open(); using (SqlBulkCopy sqlbc = new SqlBulkCopy(sqlConn)) { sqlbc.DestinationTableName = "BOM"; sqlbc.ColumnMappings.Add("Material", "Material"); sqlbc.ColumnMappings.Add("Plnt", "Plnt"); sqlbc.ColumnMappings.Add("Level", "Level"); sqlbc.ColumnMappings.Add("Item", "Item"); sqlbc.ColumnMappings.Add("Component", "Component"); sqlbc.ColumnMappings.Add("Object description", "Object description"); sqlbc.WriteToServer(dt); Response.Write("數據導入成功!"); } } } catch (Exception ex) { throw ex; }
Source Code


演示:
技術分享

讀取Excel的記錄並導入SQL數據庫