1. 程式人生 > >在ASP.NET中將Excel檔案中資料匯入資料庫並顯示進度條

在ASP.NET中將Excel檔案中資料匯入資料庫並顯示進度條

在ASP.NET中經常會遇到Excel檔案匯入資料庫的問題,遇到資料量比較大的時候,最好顯示進度條。

進度條設計是參考網上某牛人提供的程式碼,利用JS實現的,謝謝這個大牛了(忘記了當時記錄下他的大名了,:()。具體思路:首先將後臺伺服器上ProgressBar.htm 頁面內容(其中有html和js程式碼)完全讀取出來,並write到前臺。然後在資料匯入前,新增js呼叫,如下:

 jsBlock = "<script>BeginTrans('開始處理...');</script>";

 Response.Write(jsBlock);
 Response.Flush();

其次,在處理每條資料匯入的過程中,新增如下js呼叫:

 System.Threading.Thread.Sleep(20);

 float cposf = 0;
 cposf = 100 * i / maxrows;
 int cpos = (int)cposf;

 jsBlock = "<script>SetPorgressBar('" + "第" + i.ToString() + "條','" + cpos.ToString() + "');</script>";
 Response.Write(jsBlock);
 Response.Flush();

*******************************************************

以下是完整的實現過程......

前臺.aspx部分程式碼:

<tr>
       <td align="center" style="height: 25px; width: 100px;">父分類</td>
       <td valign="middle" style="height: 25px">
       <asp:TextBox ID="tbParent" runat="server" CssClass="textinput" Text="" Width="150px"></asp:TextBox>
       <asp:TextBox ID="tbParentId" runat="server" CssClass="textinput" Text=""Width="19px" ></asp:TextBox>
       <asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="Red" Text="不能為空"
                                                    Visible="False"></asp:Label></td>
</tr>
<tr>
       <td align="center" style="height: 24px; width: 100px;"> Excel檔案</td>
       <td style="height: 24px">
       <asp:FileUpload ID="fuGlossaryXls" runat="server" />
       <asp:Label ID="Label2" runat="server" Font-Bold="True" ForeColor="Red" Text="不能為空"
                                                    Visible="False"></asp:Label></td>
</tr>

... ... ...

<asp:Button ID="btnImport" runat="server" CssClass="mybotton" Text="導  入" Width="60px" OnClick="btnImport_Click" ></asp:Button> 

以下是在FileUpload控制元件中,選擇了相應檔案後點擊“匯入”.aspx.cs檔案中響應事件。

protected void btnImport_Click(object sender, EventArgs e)
    {
        string cparentname = this.tbParent.Text.Trim();
        string cparentid = this.tbParentId.Text.Trim();
        if (cparentname == "")
        {
            Label1.Visible = true;
            return;
        }
        else
        {
            Label1.Visible = false;
        }

        string cfilename = this.fuGlossaryXls.FileName;
        if (cfilename == "")
        {
            Label2.Visible = true;
            return;
        }
        else
        {
            Label2.Visible = false;
        }

        //////////////首先將檔案上傳到伺服器///////////////////////////////////////////////////////////  
        string tempfilename = Guid.NewGuid().ToString();
        String filepath = System.Configuration.ConfigurationSettings.AppSettings["SaveFilePath"] + tempfilename + ".xls";
        try
        {
            fuGlossaryXls.SaveAs(filepath);
        }
        catch (Exception ex)
        {
            //Response.Write("<script>alert('資料檔案上傳出錯!')</script>");
            Response.Write(ex.Message);
            return;
        }
        //////////////檔案上傳到伺服器////////////////////////////////////////////////////////////


        //////////////顯示進度/////////////////////////////////////////////////////////////////////////////
        DateTime startTime = System.DateTime.Now;
        DateTime endTime = System.DateTime.Now;

        // 根據 ProgressBar.htm 顯示進度條介面
        string templateFileName = Path.Combine(Server.MapPath("."), "ProgressBar.htm");
        StreamReader reader = new StreamReader(@templateFileName, System.Text.Encoding.GetEncoding("gb2312"));
        string html = reader.ReadToEnd();
        reader.Close();
        Response.Write(html);
        Response.Flush();
        System.Threading.Thread.Sleep(1000);

        string jsBlock;
        // 處理完成
        jsBlock = "<script>BeginTrans('開始處理...');</script>";
        Response.Write(jsBlock);
        Response.Flush();

        ///--------------------------------------------------
        object missing = Missing.Value;
        DateTime beforeTime;
        DateTime afterTime;

        beforeTime = DateTime.Now;
        Excel.Application cexcelapp = new Excel.Application();
        cexcelapp.Visible = false;
        afterTime = DateTime.Now;

        Excel.Workbook workBook = cexcelapp.Workbooks.Open(filepath, missing, missing, missing, missing, missing,
                                missing, missing, missing, missing, missing, missing, missing, missing, missing);

        //得到WorkSheet物件
        Excel.Worksheet sheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);

        int maxrows = 0;
        int maxcolumns = 0;
        maxrows = sheet.UsedRange.Rows.Count;
        maxcolumns = sheet.UsedRange.Columns.Count;
        ///--------------------------------------------------

        System.Threading.Thread.Sleep(200);

        bool err = false;

        // 根據處理任務處理情況更新進度條
        for (int i = 1; i <= maxrows; i++)
        {
            ///-------------處理-------------------------------------
            Range curentCell = (Range)sheet.Cells[i, 1];
            string cvalue = curentCell.Text.ToString().Trim();
            if (cvalue != "")
            {
                //bool exist = CommFun.DataItemExistCheck("GLOSSARY", "NODE_NAME", cvalue);
                string cwherestr = " parent_id = '" + cparentid + "'";
                bool exist = CommFun.DataItemExistCheck("GLOSSARY", "NODE_NAME", cvalue, cwherestr);
                if (!exist)
                {
                    string newnodeid = Glossary.GetNewnodeId(cparentid);
                    int subresult = Glossary.AddNode(newnodeid, cvalue, cparentid);
                    if (subresult != 0)
                    {
                        jsBlock = "<script>EndTrans('資料寫入錯誤。');</script>";
                        Response.Write(jsBlock);
                        Response.Flush();
                        err = true;
                        break;
                    }
                }
            }
           
            ///-----------------------------------------------------
            System.Threading.Thread.Sleep(20);

            float cposf = 0;
            cposf = 100 * i / maxrows;
            int cpos = (int)cposf;

            jsBlock = "<script>SetPorgressBar('" + "第" + i.ToString() + "條','" + cpos.ToString() + "');</script>";
            Response.Write(jsBlock);
            Response.Flush();
        }

        if (!err)
        {
            // 處理完成
            jsBlock = "<script>EndTrans('處理完成。');</script>";
            Response.Write(jsBlock);
            Response.Flush();
        }
        // 用時
        endTime = DateTime.Now;
        jsBlock = "<script>SetTimeInfo('用時" + GetTimeSpan(startTime, endTime) + "');</script>";
        Response.Write(jsBlock);
        Response.Flush();
        //////////////////顯示進度/////////////////////////////////////////////////////////////////////////////////////
       

        try
        {
            workBook.Close(null, null, null);
            cexcelapp.Workbooks.Close();
            cexcelapp.Application.Quit();
            cexcelapp.Quit();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(cexcelapp);

            workBook = null;
            cexcelapp = null;

            GC.Collect();
        }
        catch (Exception e1)
        {
            throw e1;
        }
        finally
        {
            Process[] myProcesses;
            DateTime startTime1;
            myProcesses = Process.GetProcessesByName("Excel");

            //得不到Excel程序ID,暫時只能判斷程序啟動時間
            foreach (Process myProcess in myProcesses)
            {
                startTime1 = myProcess.StartTime;

                if (startTime1 > beforeTime && startTime < afterTime)
                {
                    myProcess.Kill();
                }
            }
        }

        System.IO.File.Delete(filepath);
    }

ProgressBar.htm 檔案內容如下:

<html>
<head>
<title></title>
<script language="javascript">

//開始處理
function BeginTrans(msg)
{
    WriteText("Msg1",msg);
}

//設定進度條進度
function SetPorgressBar(msg, pos)
{
    ProgressBar.style.width= pos + "%";
    WriteText("Msg1",msg + " 已完成" + pos + "%");
}

//處理結束
function EndTrans(msg)
{
    if(msg=="")
        WriteText("Msg1","完成。");
    else
        WriteText("Msg1",msg);
}

//設定時間資訊
function SetTimeInfo(msg)
{
    WriteText("Msg2",msg);
}

// 更新文字顯示資訊
function WriteText(id, str)
{
 var strTag = '<font face="Verdana, Arial, Helvetica" size="2" color="#ea9b02"><B>' + str + '</B></font>'; 
 if (document.all) document.all[id].innerHTML = strTag;
}
</script>
</head>
<body>
<table align="center" style="height:100%">
    <tr style="height:45%"><td></td></tr>
    <tr>
        <td>
            <div id="Msg1" style="height:16px;">
            <font face="Verdana, Arial, Helvetica" size="2" color="#ea9b02"><b>正在載入...</b></font></div>
            <div id="ProgressBarSide" style="width:300px; color:Silver;border-width:1px; border-style:Solid;">
                <div id="ProgressBar" align="center" style="height:20px; width:0%; background-color:#316AC5;"></div>
            </div>
            <div id="Msg2" style="height:16px;"><font face="Verdana, Arial, Helvetica" size="2" color="#ea9b02"><b></b></font></div>
        </td>
    </tr>
    <tr style="height:50%"><td></td></tr>
</table>
</body>
</html>