Asp.net導入Excel數據文件


實現頁面選擇查找文件,並導入以如下結構為模板的Excel數據文件

 

前台設計界面如下:

在這里使用asp.net的FileUpload控件實現文件查找選擇,前台代碼如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <base target="_self" />
</head>
<body style="height: 380px; width: 1000px; background-color: #B9D3EE;">
    <form id="form1" runat="server">
        <div style="margin-top: 50px; margin-left: 50px;">
            <div style="height: 38px">
                <asp:Label runat="server" Text="文件*:" Width="60px"></asp:Label>
                <asp:FileUpload ID="fulImport" runat="server" Height="20px" Width="450px" />
            </div>
            <div style="height: 68px; margin-top: 60px;">
                <div style="float: left; margin-left: 85px">
                    <asp:Button ID="btnImport" runat="server" Text="上傳" Width="60px" Height="30px" OnClick="btnImport_Click" />
                </div>
                <div style="float: left; margin-left: 60px">
                    <asp:Button ID="btnClose" runat="server" Text="關閉" Width="60px" Height="30px" OnClick="btnClose_Click" />
                </div>
            </div>
        </div>
    </form>
</body>
</html>

選擇文件后點擊上傳按鈕觸發后台點擊事件。

      /// <summary>
        /// 上傳導入按鈕點擊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                //文件名
                string strFileName = fulImport.FileName;

                //驗證是否選擇了文件
                if ("" == strFileName.Trim())
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('請選擇文件!');", true);
                    return;
                }

                //驗證文件類型是不是Excel
                if (strFileName.Substring(strFileName.LastIndexOf('.')) != ".xlsx" && strFileName.Substring(strFileName.LastIndexOf('.')) != ".xls")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('文件類型錯誤!'", true);
                    return;
                }

                //獲取上載文件內容
                string Attachment = "";//附件
                //string strFilePath = ConfigurationManager.AppSettings["tempFilePath"].ToString();
                string strFilePath = "./tem/";
                strFilePath = Server.MapPath(strFilePath);
                Attachment = fulImport.funString_FileUpLoadAttachmentABPath(strFileName, 50, strFilePath);

                string strPath = strFilePath + Attachment;
                fulImport.PostedFile.SaveAs(strPath);
                DataSet ds = GetExcelData(strPath);

                //判斷文件內容是否為空
                if (ds == null)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('這個文件沒有數據!');", true);
                    return;
                }

                int i_count = 0;//計算行數
                IdioSoft.Common.Method.DbSQLAccess objDbSQLAccess = new IdioSoft.Common.Method.DbSQLAccess(SqlCon);
                //導入到數據庫
                try
                {
                    int result = 0;
                    foreach (DataTable dt in ds.Tables)
                    {
                        try
                        {
                            string strRow = dt.Rows[0]["工廠"].ToString();//判斷行是否存在
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        //行數存在,累加行數
                        i_count++;
                        string strFactory = "";
                        string strWorkshop = "";
                        string strQualityDoor = "";
                        string strFirstPartStructure = "";
                        string strSecondPartStructure = "";

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            strFactory = dt.Rows[i]["工廠"].ToString();
                            strWorkshop = dt.Rows[i]["車間"].ToString();
                            strQualityDoor = dt.Rows[i]["質量門"].ToString();
                            strFirstPartStructure = dt.Rows[i]["一級零部件結構"].ToString();
                            strSecondPartStructure = dt.Rows[i]["二級零部件結構"].ToString();

                            //判斷行數據是否完整並給出提示
                            if (strFactory == "" || strWorkshop == "" || strQualityDoor == "" || strFirstPartStructure == "" || strSecondPartStructure == "")
                            {
                                int m = i + 1;
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('第" + m + "行數據不完整!')", true);
                                return;
                            }
                            else//數據完整則插入數據庫
                            {
                                string strSqlDelete = string.Format(@"
                                                                    DELETE FROM [Test].[dbo].[QMS_QualiryDoorAndParts]
                                                                            WHERE [Factory]=N'{0}' AND [Workshop]=N'{1}' AND [QualityDoor]=N'{2}' 
                                                                                    AND [FirstPartStructure]=N'{3}' AND [SecondPartStructure]=N'{4}'
                                                                    ", strFactory, strWorkshop, strQualityDoor, strFirstPartStructure, strSecondPartStructure);
                                objDbSQLAccess.funString_SQLExecuteScalar(strSqlDelete);
                                string strSqlInsert = string.Format(@"
                                                                    INSERT INTO [Test].[dbo].[QMS_QualiryDoorAndParts]
                                                                            ([Factory]
                                                                            ,[Workshop]
                                                                            ,[QualityDoor]
                                                                            ,[FirstPartStructure]
                                                                            ,[SecondPartStructure])
                                                                        VALUES
                                                                            (N'{0}'
                                                                            ,N'{1}'
                                                                            ,N'{2}'
                                                                            ,N'{3}'
                                                                            ,N'{4}')
                                                                            ",strFactory ,strWorkshop ,strQualityDoor,strFirstPartStructure, strSecondPartStructure);
                                result = objDbSQLAccess.funString_SQLExecuteScalar(strSqlInsert).funInt_StringToInt(0);
                            }
                        }
                    }
                    if (result == 0 && i_count > 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('導入成功。');", true);
                    }
                    else if (i_count == 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('EXEC中的列名不符合規則。');", true);
                    }
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('Fail:" + ex.Message + "');", true);
                }
            }
            catch (Exception exp)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('Fail:" + exp.Message + "');", true);
            }
        }

 

后台完整實現代碼如下:

其中IdioSoft.Common.Method;是類似SQLHelper的一個引用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using IdioSoft.Common.Method;

namespace QualityDoorAndPartsCorrespondence
{
    public partial class QualityDoorAndPartsImport : System.Web.UI.Page
    {
        #region...頁面屬性...

        /// <summary>
        /// 數據庫連接字符串//web.config文件中數據庫的聯接串name
        /// </summary>
        private static string SqlCon
        {
            get
            {
                return "MES-Conn";
            }
        }

        #endregion...頁面屬性...

        #region...方法...

        /// <summary>
        /// 唯一需要注意的是,如果目標機器的操作系統,是64位的話。
        /// 項目需要 編譯為 x86,而不是簡單的使用默認的 Any CPU.
        /// </summary>
        /// <param name="strExcelFileName"></param>
        /// <returns></returns>
        private string GetOleDbConnectionString(string strExcelFileName)
        {
            // Office 2007 以及 以下版本使用.
            string strJETConnString =
              String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", strExcelFileName);
            // xlsx 擴展名 使用.
            string strASEConnXlsxString =
              String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"", strExcelFileName);
            // xls 擴展名 使用.
            string strACEConnXlsString =
              String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\"", strExcelFileName);
            //其他
            string strOtherConnXlsString =
              String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", strExcelFileName);

            //嘗試使用 ACE. 假如不發生錯誤的話,使用 ACE 驅動.
            try
            {
                System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection(strACEConnXlsString);
                cn.Open();
                cn.Close();
                // 使用 ACE
                return strACEConnXlsString;
            }
            catch (Exception)
            {
                // 啟動 ACE 失敗.
            }

            // 嘗試使用 Jet. 假如不發生錯誤的話,使用 Jet 驅動.
            try
            {
                System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection(strJETConnString);
                cn.Open();
                cn.Close();
                // 使用 Jet
                return strJETConnString;
            }
            catch (Exception)
            {
                // 啟動 Jet 失敗.
            }

            // 嘗試使用 Jet. 假如不發生錯誤的話,使用 Jet 驅動.
            try
            {
                System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection(strASEConnXlsxString);
                cn.Open();
                cn.Close();
                // 使用 Jet
                return strASEConnXlsxString;
            }
            catch (Exception)
            {
                // 啟動 Jet 失敗.
            }
            // 假如 ACE 與 JET 都失敗了,默認使用 JET.
            return strOtherConnXlsString;
        }

        /// <summary>
        /// 獲取Excel數據
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private DataSet GetExcelData(string strFilePath)
        {
            try
            {
                //獲取連接字符串
                // @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;HDR=YES;";
                string strConn = GetOleDbConnectionString(strFilePath);

                DataSet ds = new DataSet();
                using (OleDbConnection conn = new OleDbConnection(strConn))
                {
                    //打開連接
                    conn.Open();
                    System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                    // 取得Excel工作簿中所有工作表  
                    System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    OleDbDataAdapter sqlada = new OleDbDataAdapter();

                    foreach (DataRow dr in schemaTable.Rows)
                    {
                        try
                        {
                            string strSql = "Select * From [" + dr[2].ToString().Trim() + "]";
                            if (strSql.Contains("$"))
                            {
                                OleDbCommand objCmd = new OleDbCommand(strSql, conn);
                                sqlada.SelectCommand = objCmd;
                                sqlada.Fill(ds, dr[2].ToString().Trim());
                            }
                        }
                        catch { }
                    }
                    //關閉連接
                    conn.Close();
                }
                return ds;
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "err", "alert('" + ex.Message + "');", false);
                return null;
            }
        }



        #endregion...方法...

        #region...事件...

        /// <summary>
        /// 頁面加載
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 上傳導入按鈕點擊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                //文件名
                string strFileName = fulImport.FileName;

                //驗證是否選擇了文件
                if ("" == strFileName.Trim())
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('請選擇文件!');", true);
                    return;
                }

                //驗證文件類型是不是Excel
                if (strFileName.Substring(strFileName.LastIndexOf('.')) != ".xlsx" && strFileName.Substring(strFileName.LastIndexOf('.')) != ".xls")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('文件類型錯誤!'", true);
                    return;
                }

                //獲取上載文件內容
                string Attachment = "";//附件
                //string strFilePath = ConfigurationManager.AppSettings["tempFilePath"].ToString();
                string strFilePath = "./tem/";
                strFilePath = Server.MapPath(strFilePath);
                Attachment = fulImport.funString_FileUpLoadAttachmentABPath(strFileName, 50, strFilePath);

                string strPath = strFilePath + Attachment;
                fulImport.PostedFile.SaveAs(strPath);
                DataSet ds = GetExcelData(strPath);

                //判斷文件內容是否為空
                if (ds == null)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('這個文件沒有數據!');", true);
                    return;
                }

                int i_count = 0;//計算行數
                IdioSoft.Common.Method.DbSQLAccess objDbSQLAccess = new IdioSoft.Common.Method.DbSQLAccess(SqlCon);
                //導入到數據庫
                try
                {
                    int result = 0;
                    foreach (DataTable dt in ds.Tables)
                    {
                        try
                        {
                            string strRow = dt.Rows[0]["工廠"].ToString();//判斷行是否存在
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        //行數存在,累加行數
                        i_count++;
                        string strFactory = "";
                        string strWorkshop = "";
                        string strQualityDoor = "";
                        string strFirstPartStructure = "";
                        string strSecondPartStructure = "";

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            strFactory = dt.Rows[i]["工廠"].ToString();
                            strWorkshop = dt.Rows[i]["車間"].ToString();
                            strQualityDoor = dt.Rows[i]["質量門"].ToString();
                            strFirstPartStructure = dt.Rows[i]["一級零部件結構"].ToString();
                            strSecondPartStructure = dt.Rows[i]["二級零部件結構"].ToString();

                            //判斷行數據是否完整並給出提示
                            if (strFactory == "" || strWorkshop == "" || strQualityDoor == "" || strFirstPartStructure == "" || strSecondPartStructure == "")
                            {
                                int m = i + 1;
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('第" + m + "行數據不完整!')", true);
                                return;
                            }
                            else//數據完整則插入數據庫
                            {
                                string strSqlDelete = string.Format(@"
                                                                    DELETE FROM [Test].[dbo].[QMS_QualiryDoorAndParts]
                                                                            WHERE [Factory]=N'{0}' AND [Workshop]=N'{1}' AND [QualityDoor]=N'{2}' 
                                                                                    AND [FirstPartStructure]=N'{3}' AND [SecondPartStructure]=N'{4}'
                                                                    ", strFactory, strWorkshop, strQualityDoor, strFirstPartStructure, strSecondPartStructure);
                                objDbSQLAccess.funString_SQLExecuteScalar(strSqlDelete);
                                string strSqlInsert = string.Format(@"
                                                                    INSERT INTO [Test].[dbo].[QMS_QualiryDoorAndParts]
                                                                            ([Factory]
                                                                            ,[Workshop]
                                                                            ,[QualityDoor]
                                                                            ,[FirstPartStructure]
                                                                            ,[SecondPartStructure])
                                                                        VALUES
                                                                            (N'{0}'
                                                                            ,N'{1}'
                                                                            ,N'{2}'
                                                                            ,N'{3}'
                                                                            ,N'{4}')
                                                                            ",strFactory ,strWorkshop ,strQualityDoor,strFirstPartStructure, strSecondPartStructure);
                                result = objDbSQLAccess.funString_SQLExecuteScalar(strSqlInsert).funInt_StringToInt(0);
                            }
                        }
                    }
                    if (result == 0 && i_count > 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('導入成功。');", true);
                    }
                    else if (i_count == 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('EXEC中的列名不符合規則。');", true);
                    }
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('Fail:" + ex.Message + "');", true);
                }
            }
            catch (Exception exp)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "JsError", "alert('Fail:" + exp.Message + "');", true);
            }
        }

        /// <summary>
        /// 關閉按鈕點擊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            //關閉頁面
            Response.Write("<script>window.opener=null;window.close();</script>");
        }

        #endregion...事件...

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM