Asp.net中Excel數據導入到SQL Server

1、首先在前臺添加一個upfileload文件上傳控件和一個button按鈕,upfileload上傳控件用於讀取Excel文件!

2、GetExcelData()函數用於讀取Excel文件並填寫到一個DateSet中,由於微軟對07以後的Excel的數據結構作了修改,所以針對07以前的版本和07及其以後的版本使用不同的連接串。

        string connStr03 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;"; ;
        string connStr07 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=YES'";
由於Excel文件可能無法讀取到,在讀取之前最好先將文件上傳:

inputFile.SaveAs(Server.MapPath("~/" + System.IO.Path.GetFileName(inputFile.PostedFile.FileName)));

string filePath = Server.MapPath("~/" + System.IO.Path.GetFileName(inputFile.PostedFile.FileName));

3、InsertDB()函數用於將存儲Excel數據的DateSet中的數據導入到SQL Server中。

具體代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Data.OleDb;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    /// <summary>
    /// 該方法實現從Excel中導出數據到DataSet中,其中filepath爲Excel文件的絕對路徑,sheetname爲表示那個Excel表,此用Sheet1;
    /// </summary>
    /// <param name="ds">ds</param>
    private void InsertDB(DataSet ds)
    {
        string CONNECTION_STRING = @"Data Source=(local); Initial Catalog=test;Integrated Security=false;User ID=sa;Password=sa;";
        SqlConnection _con = new SqlConnection(CONNECTION_STRING);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = _con;
        StringBuilder sb = new StringBuilder();
        if (ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                sb.Append(" insert into ynzt6(time,cul1,cul2,cul3,cul4) values('");
                sb.Append(ds.Tables[0].Rows[i].ItemArray[0].ToString() + "','");
                sb.Append(ds.Tables[0].Rows[i].ItemArray[1].ToString() + "','");
                sb.Append(ds.Tables[0].Rows[i].ItemArray[2].ToString() + "','");
                sb.Append(ds.Tables[0].Rows[i].ItemArray[3].ToString() + "','");
                sb.Append(ds.Tables[0].Rows[i].ItemArray[4].ToString() + "' ) ");
                cmd.CommandText = sb.ToString();
            }
        }
        _con.Open();
        int j = cmd.ExecuteNonQuery();
        _con.Close();
        if (j > 0)
        {
            lblMessage.Text = "Insert into PDB_YN_BEF table Sucessfully!";
        }
    }
    /// <summary>
    /// get data source from excel file
    /// </summary>
    /// <returns>dataset ds</returns>
    private DataSet GetExcelData()
    {
        DataSet ds = new DataSet();
        inputFile.SaveAs(Server.MapPath("~/" + System.IO.Path.GetFileName(inputFile.PostedFile.FileName)));
        string filePath = Server.MapPath("~/" + System.IO.Path.GetFileName(inputFile.PostedFile.FileName));
        string connStr03 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;"; ;
        string connStr07 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=YES'";
        string queryStr = "SELECT * FROM [Sheet1$]";
        OleDbConnection conn03 = new OleDbConnection(connStr03);
        OleDbConnection conn07 = new OleDbConnection(connStr07);
        if (inputFile.HasFile)
        {
            string fileExt = System.IO.Path.GetExtension(inputFile.FileName);
            if (fileExt == ".xls")
            {
                OleDbDataAdapter myAdapter = new OleDbDataAdapter(queryStr, conn03);
                myAdapter.Fill(ds);
            }
            else if (fileExt == ".xlsx")
            {
                OleDbDataAdapter myAdapter = new OleDbDataAdapter(queryStr, conn07);
                myAdapter.Fill(ds);
            }
            else
            {
                lblMessage.Text = "The file is not exist!";
            }

        }
        return ds;
    }
    protected void btnUpload_Click1(object sender, EventArgs e)
    {
        DataSet ds = GetExcelData();
        InsertDB(ds);

    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章