asp.net實現excel資料到sql server的匯入

來源:互聯網
上載者:User

針對網上的一些程式碼片段,增加了程式的健壯性控制.

前台介面如下:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>無標題頁</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fuOpen" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="匯入" onclick="btnUpload_Click" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

後台代碼:

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //確保已經選擇了待匯入的檔案,首先上傳,然後在伺服器端完成匯入
        if (this.fuOpen.PostedFile.FileName != "")
        {
            //確保檔案是excel格式
            //Response.Write(this.fuOpen.FileName.Substring(this.fuOpen.FileName.LastIndexOf('.')));
            if (this.fuOpen.FileName.Substring(this.fuOpen.FileName.LastIndexOf('.')+1) == "xls")
            {
                Random rd = new Random(1);
                string filename = DateTime.Now.Date.ToString("yyyymmdd") + DateTime.Now.ToLongTimeString().Replace(":", "") + rd.Next(9999).ToString() + ".xls";
                try
                {
                    this.fuOpen.PostedFile.SaveAs(@Server.MapPath("fileupload/") + filename);
                }
                catch (HttpException he)
                {
                    Response.Write("檔案上傳不成功,請檢查檔案是否過大,是否有寫入權限!");
                    return;
                }
                #region --------讀取檔案內容到伺服器記憶體----------
                string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + Server.MapPath("fileupload") + "/" + filename + ";Extended Properties=Excel 8.0";
                OleDbConnection thisconnection = new OleDbConnection(conn);
                thisconnection.Open();
                //要保證欄位名和excel表中的欄位名相同
                string Sql = "select StuName,MajorID,CardID from [Sheet1$]";
                OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, thisconnection);
                DataSet ds = new DataSet();
                mycommand.Fill(ds, "[Sheet1$]");
                thisconnection.Close();
                this.GridView1.DataSource = ds;
                this.GridView1.DataBind();
                #endregion

                #region --------插入到資料庫中---------
                string conn1 = "User ID=sa;Data Source=127.0.0.1//SQLSERVER;Password=sa;Initial Catalog=Fee;Provider=SQLOLEDB.1;";
                OleDbConnection thisconnection1 = new OleDbConnection(conn1);
                thisconnection1.Open();
                int count = ds.Tables["[Sheet1$]"].Rows.Count;

                for (int i = 0; i < count; i++)
                {
                    string stuName, majorID, cardID;
                    stuName = ds.Tables["[Sheet1$]"].Rows[i]["StuName"].ToString();
                    majorID = ds.Tables["[Sheet1$]"].Rows[i]["majorID"].ToString();
                    cardID = ds.Tables["[Sheet1$]"].Rows[i]["cardid"].ToString();
                    //id_3 = ds.Tables["[Sheet1$]"].Rows[i]["id_3"].ToString();
                    string excelsql = "insert into Fee_stu(stuname,majorid,cardid) values ('" + stuName + "','" + majorID + "','" + cardID + "') ";
                    OleDbCommand mycommand1 = new OleDbCommand(excelsql, thisconnection1);
                    try
                    {
                        mycommand1.ExecuteNonQuery();
                    }
                    catch (OleDbException ode)
                    {
                        Response.Write( "<b>匯入不成功,請重試!</b>");
                        return;
                    }
                }
                Response.Write("更新成功");
                thisconnection1.Close();
                #endregion
            }
            else
            {
                Response.Write("匯入檔案的格式不正確!");
            }

        }
        else
        {
            Response.Write("您還沒有選擇要匯入的檔案!");
        }

  }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.