結合bootstrap fileinput插件和Bootstrap-table表格插件,實現文件上傳、預覽、提交的導入Excel數據操做流程

一、bootstrap-fileinpu的簡單介紹

在前面的隨筆,我介紹了Bootstrap-table表格插件的具體項目應用過程,本篇隨筆介紹另一個Bootstrap FieInput插件的使用,整合二者能夠實現咱們常規的Web數據導入操做,導入數據操做過程包括有上傳文件,預覽數據,選擇並提交記錄等一系列操做。javascript

關於這個插件,我在早期隨筆《Bootstrap文件上傳插件File Input的使用》也作了一次介紹,這是一個加強的 HTML5 文件輸入控件,是一個 Bootstrap 3.x 的擴展,實現文件上傳預覽,多文件上傳等功能。css

bootstrap-fileinput源碼:https://github.com/kartik-v/bootstrap-fileinputhtml

bootstrap-fileinput在線API:http://plugins.krajee.com/file-input前端

bootstrap-fileinput Demo展現:http://plugins.krajee.com/file-basic-usage-demojava

這個插件主要是介紹如何處理圖片上傳的處理操做,原先個人Excel導入操做使用的是Uploadify插件,能夠參考我隨筆《附件上傳組件uploadify的使用》,不過這個須要Flash控件支持,在某些瀏覽器(如Chrome)就比較麻煩了,所以決定使用一種較爲通用的上傳插件,此次首先對基於Bootstrap前端架構的框架系統進行升級,替代原來的Uploadify插件,這樣頁面上傳功能,在各個瀏覽器就能夠無差別的實現了。git

通常狀況下,咱們須要引入下面兩個文件,插件才能正常使用:github

bootstrap-fileinput/css/fileinput.min.css
bootstrap-fileinput/js/fileinput.min.js

在File input 插件使用的時候,若是是基於Asp.NET MVC的,那麼咱們可使用BundleConfig.cs進行添加對應的引用,加入到Bundles集合引用便可。ajax

    //添加對bootstrap-fileinput控件的支持
    css_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/css/fileinput.min.css");
    js_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/fileinput.min.js");
    js_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/locales/zh.js");

在頁面中,咱們使用如下HTML代碼實現界面展現,主要的bootstrap fileinput插件聲明,主要是基礎的界面代碼數據庫

<input id="excelFile" type="file"> 

Excel導入的的界面展現以下所示。json

選擇指定文件後,咱們能夠看到Excel的文件列表,以下界面所示。

上傳文件後,數據直接展現在彈出層的列表裏面,這裏直接使用了 Bootstrap-table表格插件進行展現。

這樣咱們就能夠把Excel的記錄展現出來,實現了預覽的功能,勾選必要的記錄,而後保存便可提交到服務器進行保存,實現了Excel數據的真正導入數據庫處理。

 

二、Excel導出操做詳細介紹

咱們在實際導入Excel的界面中,HTML代碼以下所示。

<!--導入數據操做層-->
<div id="import" class="modal fade bs-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                <h4 class="modal-title">文件導入</h4>
            </div>
            <div class="modal-body">
                <div style="text-align:right;padding:5px">
                    <a href="~/Content/Template/TestUser-模板.xls" onclick="javascript:Preview();">
                        <img alt="測試用戶信息-模板" src="~/Content/images/ico_excel.png" />
                        <span style="font-size:larger;font-weight:200;color:red">TestUser-模板.xls</span>
                    </a>
                </div>
                <hr/>
                <form id="ffImport" method="post">
                    <div title="Excel導入操做" style="padding: 5px">
                        <input type="hidden" id="AttachGUID" name="AttachGUID" /> 
                        <input id="excelFile" type="file"> 
                    </div>
                </form>

                <!--數據顯示錶格-->
                <table id="gridImport" class="table table-striped table-bordered table-hover" cellpadding="0" cellspacing="0" border="0">
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
                <button type="button" class="btn btn-primary" onclick="SaveImport()">保存</button>
            </div>
        </div>
    </div>
</div>

對於bootstrap fileinput的各類屬性,咱們這裏使用JS進行初始化,這樣方便統一管理和修改。

        //初始化Excel導入的文件
        function InitExcelFile() {
            //記錄GUID
            $("#AttachGUID").val(newGuid());

            $("#excelFile").fileinput({
                uploadUrl: "/FileUpload/Upload",//上傳的地址
                uploadAsync: true,              //異步上傳
                language: "zh",                 //設置語言
                showCaption: true,              //是否顯示標題
                showUpload: true,               //是否顯示上傳按鈕
                showRemove: true,               //是否顯示移除按鈕
                showPreview : true,             //是否顯示預覽按鈕
                browseClass: "btn btn-primary", //按鈕樣式 
                dropZoneEnabled: false,         //是否顯示拖拽區域
                allowedFileExtensions: ["xls", "xlsx"], //接收的文件後綴
                maxFileCount: 1,                        //最大上傳文件數限制
                previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
                allowedPreviewTypes: null,
                previewFileIconSettings: {
                    'docx': '<i class="glyphicon glyphicon-file"></i>',
                    'xlsx': '<i class="glyphicon glyphicon-file"></i>',
                    'pptx': '<i class="glyphicon glyphicon-file"></i>',
                    'jpg': '<i class="glyphicon glyphicon-picture"></i>',
                    'pdf': '<i class="glyphicon glyphicon-file"></i>',
                    'zip': '<i class="glyphicon glyphicon-file"></i>',
                },
                uploadExtraData: {  //上傳的時候,增長的附加參數
                    folder: '數據導入文件', guid: $("#AttachGUID").val()
                }
            })  //文件上傳完成後的事件
           .on('fileuploaded', function (event, data, previewId, index) {
                var form = data.form, files = data.files, extra = data.extra,
                    response = data.response, reader = data.reader;

                var res = data.response; //返回結果
                if (res.Success) {
                    showTips('上傳成功');
                    var guid = $("#AttachGUID").val();

                    //提示用戶Excel格式是否正常,若是正常加載數據
                    $.ajax({
                        url: '/TestUser/CheckExcelColumns?guid=' + guid,
                        type: 'get',
                        dataType: 'json',
                        success: function (data) {
                            if (data.Success) {
                                InitImport(guid); //從新刷新表格數據
                                showToast("文件已上傳,數據加載完畢!");

                                //從新刷新GUID,以及清空文件,方便下一次處理
                                RefreshExcel();
                            }
                            else {
                                showToast("上傳的Excel文件檢查不經過。請根據頁面右上角的Excel模板格式進行數據錄入。", "error");
                            }
                        }
                    });
                }
                else {
                    showTips('上傳失敗');
                }
           });
        }

上面的邏輯具體就是,設置上傳文件的後臺頁面爲:/FileUpload/Upload,以及各類插件的配置參數,uploadExtraData裏面設置的是提交的附加參數,也就是後臺控制器接收的參數,其中

.on('fileuploaded', function (event, data, previewId, index) {

的函數處理文件上傳後的處理函數,若是上傳文件返回的結果是成功的,那麼咱們再次調用ajax來檢查這個Excel的字段是否符合要求,以下地址:

url: '/TestUser/CheckExcelColumns?guid=' + guid,

若是這個檢查的後臺返回成功的記錄,那麼再次須要把Excel記錄提取出來預覽,並清空bootstrap fileinput文件上傳插件,方便下次上傳文件。以下代碼所示。

    if (data.Success) {
        InitImport(guid); //從新刷新表格數據
        showToast("文件已上傳,數據加載完畢!");

        //從新刷新GUID,以及清空文件,方便下一次處理
        RefreshExcel();
    }
    else {
        showToast("上傳的Excel文件檢查不經過。請根據頁面右上角的Excel模板格式進行數據錄入。", "error");
    }

其中RefreshExcel就是從新更新上傳的附加參數值,方便下次上傳,不然附加參數的值一直不變化,就會致使咱們設置的GUID沒有變化而出現問題。

        //從新更新GUID的值,並清空文件
        function RefreshExcel() {
            $("#AttachGUID").val(newGuid());
            $('#excelFile').fileinput('clear');//清空全部文件
            
            //附加參數初始化後一直不會變化,若是須要發生變化,則須要使用refresh進行更新
            $('#excelFile').fileinput('refresh', {
                uploadExtraData: { folder: '數據導入文件', guid: $("#AttachGUID").val() },
            });
        }

而其中InitImport就是獲取預覽數據並展現在Bootstrap-table表格插件上的,關於這個插件的詳細使用,能夠回顧下隨筆《基於Metronic的Bootstrap開發框架經驗總結(16)-- 使用插件bootstrap-table實現表格記錄的查詢、分頁、排序等處理》進行了解便可。

        //根據條件查詢並綁定結果
        var $import;
        function InitImport(guid) {
            var url = "/TestUser/GetExcelData?guid=" + guid;
            $import = $('#gridImport').bootstrapTable({
                url: url,                           //請求後臺的URL(*)
                method: 'GET',                      //請求方式(*)
                striped: true,                      //是否顯示行間隔色
                cache: false,                       //是否使用緩存,默認爲true,因此通常狀況下須要設置一下這個屬性(*)
                pagination: false,                  //是否顯示分頁(*)
                sidePagination: "server",           //分頁方式:client客戶端分頁,server服務端分頁(*)
                pageNumber: 1,                      //初始化加載第一頁,默認第一頁,並記錄
                pageSize: 100,                     //每頁的記錄行數(*)
                pageList: [10, 25, 50, 100],        //可供選擇的每頁的行數(*)
                search: false,                      //是否顯示錶格搜索
                strictSearch: true,
                showColumns: true,                  //是否顯示全部的列(選擇顯示的列)
                showRefresh: true,                  //是否顯示刷新按鈕
                minimumCountColumns: 2,             //最少容許的列數
                clickToSelect: true,               //是否啓用點擊選中行
                uniqueId: "ID",                     //每一行的惟一標識,通常爲主鍵列
                queryParams: function (params) { },
                columns: [{
                    checkbox: true,
                    visible: true                  //是否顯示覆選框  
                }, {
                    field: 'Name',
                    title: '姓名'
                }, {
                    field: 'Mobile',
                    title: '手機'
                }, {
                    field: 'Email',
                    title: '郵箱',
                    formatter: emailFormatter
                }, {
                    field: 'Homepage',
                    title: '主頁',
                    formatter: linkFormatter
                }, {
                    field: 'Hobby',
                    title: '興趣愛好'
                }, {
                    field: 'Gender',
                    title: '性別',
                    formatter: sexFormatter
                }, {
                    field: 'Age',
                    title: '年齡'
                }, {
                    field: 'BirthDate',
                    title: '出生日期',
                    formatter: dateFormatter
                }, {
                    field: 'Height',
                    title: '身高'
                }, {
                    field: 'Note',
                    title: '備註'
                }],
                onLoadSuccess: function () {
                },
                onLoadError: function () {
                    showTips("數據加載失敗!");
                },
            });
        }

最後就是確認提交後,會經過JS提交數據到後臺進行處理,以下代碼所示。

        //保存導入的數據
        function SaveImport() {
            
            var list = [];//構造集合對象
            var rows = $import.bootstrapTable('getSelections');
            for (var i = 0; i < rows.length; i++) {
                list.push({
                    'Name': rows[i].Name, 'Mobile': rows[i].Mobile, 'Email': rows[i].Email, 'Homepage': rows[i].Homepage,
                    'Hobby': rows[i].Hobby, 'Gender': rows[i].Gender, 'Age': rows[i].Age, 'BirthDate': rows[i].BirthDate,
                    'Height': rows[i].Height, 'Note': rows[i].Note
                });
            }

            if (list.length == 0) {
                showToast("請選擇一條記錄", "warning");
                return;
            }

            var postData = { 'list': list };//能夠增長其餘參數,如{ 'list': list, 'Rucanghao': $("#Rucanghao").val() };
            postData = JSON.stringify(postData);

            $.ajax({
                url: '/TestUser/SaveExcelData',
                type: 'post',
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                traditional: true,
                success: function (data) {
                    if (data.Success) {
                        //保存成功  1.關閉彈出層,2.清空記錄顯示 3.刷新主列表
                        showToast("保存成功");

                        $("#import").modal("hide");
                        $(bodyTag).html("");
                        Refresh();
                    }
                    else {
                        showToast("保存失敗:" + data.ErrorMessage, "error");
                    }
                },
                data: postData
            });
        }

 

三、後臺控制器代碼分析

這裏咱們的JS代碼裏面,涉及了幾個MVC後臺的方法處理:Upload、CheckExcelColumns、GetExcelData、SaveExcelData。這裏分別進行介紹。

文件上傳的後臺控制器方法以下所示。

        /// <summary>
        /// 上傳附件到服務器上
        /// </summary>
        /// <param name="fileData">附件信息</param>
        /// <param name="guid">附件組GUID</param>
        /// <param name="folder">指定的上傳目錄</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Upload(string guid, string folder)
        {
            CommonResult result = new CommonResult();

            HttpFileCollectionBase files = HttpContext.Request.Files;
            if (files != null)
            {
                foreach (string key in files.Keys)
                {
                    try
                    {
                        #region MyRegion
                        HttpPostedFileBase fileData = files[key];
                        if (fileData != null)
                        {
                            HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
                            HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
                            HttpContext.Response.Charset = "UTF-8";

                            // 文件上傳後的保存路徑
                            string filePath = Server.MapPath("~/UploadFiles/");
                            DirectoryUtil.AssertDirExist(filePath);

                            string fileName = Path.GetFileName(fileData.FileName);      //原始文件名稱
                            string fileExtension = Path.GetExtension(fileName);         //文件擴展名
                            //string saveName = Guid.NewGuid().ToString() + fileExtension; //保存文件名稱

                            FileUploadInfo info = new FileUploadInfo();
                            info.FileData = ReadFileBytes(fileData);
                            if (info.FileData != null)
                            {
                                info.FileSize = info.FileData.Length;
                            }
                            info.Category = folder;
                            info.FileName = fileName;
                            info.FileExtend = fileExtension;
                            info.AttachmentGUID = guid;

                            info.AddTime = DateTime.Now;
                            info.Editor = CurrentUser.Name;//登陸人

                            result = BLLFactory<FileUpload>.Instance.Upload(info);
                            if (!result.Success)
                            {
                                LogTextHelper.Error("上傳文件失敗:" + result.ErrorMessage);
                            }
                        } 
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        result.ErrorMessage = ex.Message;
                        LogTextHelper.Error(ex);
                    }
                }
            }
            else
            {
                result.ErrorMessage = "fileData對象爲空";
            }

            return ToJsonContent(result);
        }

文件上傳處理後,返回一個通用的CommonResult 的結果對象,也方便咱們在JS客戶端進行判斷處理。

而其中檢查咱們導入Excel的數據是否知足列要求的處理,就是判斷它的數據列和咱們預先設置好的列名是否一致便可。

        //導入或導出的字段列表   
        string columnString = "姓名,手機,郵箱,主頁,興趣愛好,性別,年齡,出生日期,身高,備註";

        /// <summary>
        /// 檢查Excel文件的字段是否包含了必須的字段
        /// </summary>
        /// <param name="guid">附件的GUID</param>
        /// <returns></returns>
        public ActionResult CheckExcelColumns(string guid)
        {
            CommonResult result = new CommonResult();

            try
            {
                DataTable dt = ConvertExcelFileToTable(guid);
                if (dt != null)
                {
                    //檢查列表是否包含必須的字段
                    result.Success = DataTableHelper.ContainAllColumns(dt, columnString);
                }
            }
            catch (Exception ex)
            {
                LogTextHelper.Error(ex);
                result.ErrorMessage = ex.Message;
            }

            return ToJsonContent(result);
        }

而GetExcelData則是格式化Excel數據到具體的List<TestUserInfo>集合裏面,這樣咱們方便在客戶端進行各類屬性的操做,它的代碼以下所示。

        /// <summary>
        /// 獲取服務器上的Excel文件,並把它轉換爲實體列表返回給客戶端
        /// </summary>
        /// <param name="guid">附件的GUID</param>
        /// <returns></returns>
        public ActionResult GetExcelData(string guid)
        {
            if (string.IsNullOrEmpty(guid))
            {
                return null;
            }

            List<TestUserInfo> list = new List<TestUserInfo>();

            DataTable table = ConvertExcelFileToTable(guid);
            if (table != null)
            {
                #region 數據轉換
                int i = 1;
                foreach (DataRow dr in table.Rows)
                {
                    bool converted = false;
                    DateTime dtDefault = Convert.ToDateTime("1900-01-01");
                    DateTime dt;
                    TestUserInfo info = new TestUserInfo();

                    info.Name = dr["姓名"].ToString();
                    info.Mobile = dr["手機"].ToString();
                    info.Email = dr["郵箱"].ToString();
                    info.Homepage = dr["主頁"].ToString();
                    info.Hobby = dr["興趣愛好"].ToString();
                    info.Gender = dr["性別"].ToString();
                    info.Age = dr["年齡"].ToString().ToInt32();
                    converted = DateTime.TryParse(dr["出生日期"].ToString(), out dt);
                    if (converted && dt > dtDefault)
                    {
                        info.BirthDate = dt;
                    }
                    info.Height = dr["身高"].ToString().ToDecimal();
                    info.Note = dr["備註"].ToString();

                    info.Creator = CurrentUser.ID.ToString();
                    info.CreateTime = DateTime.Now;
                    info.Editor = CurrentUser.ID.ToString();
                    info.EditTime = DateTime.Now;

                    list.Add(info);
                }
                #endregion
            }

            var result = new { total = list.Count, rows = list };
            return ToJsonContent(result);
        }

另外一個SaveExcelData的函數就是處理數據導入的最終處理函數,主要就是把集合寫入到具體的數據庫裏面便可,具體代碼以下所示。

        /// <summary>
        /// 保存客戶端上傳的相關數據列表
        /// </summary>
        /// <param name="list">數據列表</param>
        /// <returns></returns>
        public ActionResult SaveExcelData(List<TestUserInfo> list)
        {
            CommonResult result = new CommonResult();
            if (list != null && list.Count > 0)
            {
                #region 採用事務進行數據提交

                DbTransaction trans = BLLFactory<TestUser>.Instance.CreateTransaction();
                if (trans != null)
                {
                    try
                    {
                        //int seq = 1;
                        foreach (TestUserInfo detail in list)
                        {
                            //detail.Seq = seq++;//增長1
                            detail.CreateTime = DateTime.Now;
                            detail.Creator = CurrentUser.ID.ToString();
                            detail.Editor = CurrentUser.ID.ToString();
                            detail.EditTime = DateTime.Now;

                            BLLFactory<TestUser>.Instance.Insert(detail, trans);
                        }
                        trans.Commit();
                        result.Success = true;
                    }
                    catch (Exception ex)
                    {
                        LogTextHelper.Error(ex);
                        result.ErrorMessage = ex.Message;
                        trans.Rollback();
                    }
                }
                #endregion
            }
            else
            {
                result.ErrorMessage = "導入信息不能爲空";
            }

            return ToJsonContent(result);
        }

上面這幾個函數的代碼通常是比較有規律的,不須要一個個去編寫,通常經過代碼生成工具Database2Sharp批量生成便可。這樣能夠有效提升Web的界面代碼和後臺代碼的開發效率,減小出錯的機會。

整個導入Excel數據的處理過程,全部代碼都貼出來了,基本上整個邏輯瞭解了就能夠很好的瞭解這個過程的代碼了。

相關文章
相關標籤/搜索