基于Metronic的Bootstrap開發框架經驗總結(7)--數據的導入、導出及附件的查看處理

在很多系統模塊里面,我們可能都需要進行一定的數據交換處理,也就是數據的導入或者導出操作,這樣的批量處理能給系統用戶更好的操作體驗,也提高了用戶錄入數據的效率。我在較早時期的EasyUI的Web框架上,也介紹過通過Excel進行的數據導入導出操作,隨筆文章為《基于MVC4+EasyUI的Web開發框架經驗總結(10)--在Web界面上實現數據的導入和導出》,本文基于Bootstrap的框架基礎上,再對這個模塊進行更新處理,以及Office文檔或者圖片等附件的查看處理。

1、數據的導入操作

一般系統模塊里面,都有數據導入和導出操作,因此在界面自動生成的時候,我都傾向于給用戶自動生成這些標準的查詢、導入、導出等操作功能,界面效果如下所示。



導入操作,在Bootstrap框架里面,我把它作為一個層的,都統一放在index.cshtml文件里面,這樣可以使得整個界面的處理更加緊密一點,示例代碼如下所示。
下面這些代碼一般情況下,都是自動生成的,包括所需的全部字段,我們一般是根據需要進行字段的裁剪,以適應我們的業務和實際需要。

<!--導入數據操作層-->
<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/User-模板.xls" onclick="javascript:Preview();">
                        <img alt="測試用戶信息-模板" src="~/Content/images/ico_excel.png" />
                        <span style="font-size:larger;font-weight:200;color:red">User-模板.xls</span>
                    </a>
                </div>
                <hr/>
                <form id="ffImport" method="post">
                    <div title="Excel導入操作" style="padding: 5px" data-options="iconCls:'icon-key'">
                        <input class="easyui-validatebox" type="hidden" id="AttachGUID" name="AttachGUID" />    
                        <input id="file_upload" name="file_upload" type="file" multiple="multiple">                    
                        <a href="javascript:;" class="btn btn-primary" id="btnUpload" onclick="javascript: $('#file_upload').uploadify('upload', '*')">上傳</a>
                        <a href="javascript:;" class="btn btn-default" id="btnCancelUpload" onclick="javascript: $('#file_upload').uploadify('cancel', '*')">取消</a>

                        <div id="fileQueue" class="fileQueue"></div>
                        <br />                    
                        <hr style="width:98%" />                    
                        <div id="div_files"></div>
                        <br />                    
                    </div>
                </form>

                <!--數據顯示表格-->
                <table id="gridImport" class="table table-striped table-bordered table-hover" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
                    <thead id="gridImport_head">
                        <tr>
                            <th class="table-checkbox" style="width:40px"><input class="group-checkable" type="checkbox" onclick="selectAll(this)"></th>
                            <th>用戶編碼</th>
                            <th>用戶名/登錄名</th>
                            <th>真實姓名</th>
                            <th>職務頭銜</th>
                            <th>移動電話</th>
                            <th>辦公電話</th>
                            <th>郵件地址</th>
                            <th>性別</th>
                            <th>QQ號碼</th>
                            <th>備注</th>
                        </tr>
                    </thead>
                    <tbody id="gridImport_body"></tbody>
                </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>

我們如果要顯示導入操作界面,那么只需要把這個層顯示出來即可,如下腳本所示。

        //顯示導入界面
        function ShowImport() {
            $("#import").modal("show");
        }

這里的文件上傳處理,主要使用了Uploadify的這個控件進行處理的,當然也可以利用我前面介紹過的File Input上傳控件進行處理,都可以很好實現這些導入操作。
一般情況下的Uploadify控件的初始化代碼如下所示

$(function () {
    //添加界面的附件管理
    $('#file_upload').uploadify({
        'swf': '/Content/JQueryTools/uploadify/uploadify.swf',  //FLash文件路徑
        'buttonText': '瀏  覽',                                 //按鈕文本
        'uploader': '/FileUpload/Upload',                       //處理上傳的頁面
        'queueID': 'fileQueue',                         //隊列的ID
        'queueSizeLimit': 1,                            //隊列最多可上傳文件數量,默認為999
        'auto': false,                                  //選擇文件后是否自動上傳,默認為true
        'multi': false,                                 //是否為多選,默認為true
        'removeCompleted': true,                        //是否完成后移除序列,默認為true
        'fileSizeLimit': '10MB',                        //單個文件大小,0為無限制,可接受KB,MB,GB等單位的字符串值
        'fileTypeDesc': 'Excel Files',                  //文件描述
        'fileTypeExts': '*.xls',                        //上傳的文件后綴過濾器
        'onQueueComplete': function (event, data) {     //所有隊列完成后事件
            //業務處理代碼
            //提示用戶Excel格式是否正常,如果正常加載數據
        },
        'onUploadStart': function (file) {
            InitUpFile();//上傳文件前 ,重置GUID,每次不同
            $("#file_upload").uploadify("settings", 'formData', { 'folder': '數據導入文件', 'guid': $("#AttachGUID").val() }); //動態傳參數
        },
        'onUploadError': function (event, queueId, fileObj, errorObj) {
            //alert(errorObj.type + ":" + errorObj.info);
        }
    });
});

關鍵的邏輯就是:

//業務處理代碼

一般情況下,我們在這里已經在服務器里面獲得了Excel文件了,因此需要對這個文件的格式進行處理,如果格式正確,那么我們把數據顯示出來,供導入用戶進行記錄的選擇,決定導入那些記錄即可。



處理檢查Excel數據格式的代碼如下所示。

//提示用戶Excel格式是否正常,如果正常加載數據
$.ajax({
    url: '/User/CheckExcelColumns?guid=' + guid,
    type: 'get',
    dataType: 'json',
    success: function (data) {
        if (data.Success) {
            InitGrid(); //重新刷新表格數據
            showToast("文件已上傳,數據加載完畢!");
        }
        else {
            showToast("上傳的Excel文件檢查不通過。請根據頁面右上角的Excel模板格式進行數據錄入。", "error");
        }
    }
});

我們就是在后臺增加一個CheckExcelColumns的方法,用來檢查Excel文件的字段格式的,只有符合格式要求的文件,才被獲取數據并顯示在界面上。

顯示在界面上的JS代碼,也就是主要把Excel文件的內容提取出來,并綁定在Table元素上即可。

//根據條件查詢并綁定結果
function InitGrid() {
    var guid = $("#AttachGUID").val();
    var url = "/User/GetExcelData?guid=" + guid;
    $.getJSON(url, function (data) {
        $("#gridImport_body").html("");

        $.each(data.rows, function (i, item) {
            var tr = "<tr>";
            tr += "<td><input class='checkboxes' type=\"checkbox\" name=\"checkbox\" ></td>";
            tr += "<td>" + item.HandNo + "</td>";
            tr += "<td>" + item.Name + "</td>";
            tr += "<td>" + item.FullName + "</td>";   
            tr += "<td>" + item.Title + "</td>";
            tr += "<td>" + item.MobilePhone + "</td>";
            tr += "<td>" + item.OfficePhone + "</td>";
            tr += "<td>" + item.Email + "</td>";
            tr += "<td>" + item.Gender + "</td>";
            tr += "<td>" + item.QQ + "</td>";
            tr += "<td>" + item.Note + "</td>";

            tr += "</tr>";
            $("#gridImport_body").append(tr);
        });
    });
}

為了更進一步獲取用戶導入到具體的部門,那么我們還可以彈出一個對話框用然后選擇具體的信息,最后才提交數據到后臺進行處理。



操作代碼如下所示。

//保存導入的數據
function SaveImport() {
    //賦值給對象
    $("#Company_ID3").select2("val", @Session["Company_ID"]).trigger('change');
    $("#Dept_ID3").select2("val", @Session["Dept_ID"]).trigger('change');


    $("#selectDept").modal("show");
}

這樣我們確認保存的時候,只需要通過Ajax把數據提交給后臺處理即可,具體JS代碼如下所示。

$.ajax({
    url: '/User/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
});

Uploadify的處理在我之前基于EasyUI的界面里面也有說明,有興趣可以參考《基于MVC4+EasyUI的Web開發框架經驗總結(10)--在Web界面上實現數據的導入和導出》、《基于MVC4+EasyUI的Web開發框架形成之旅--附件上傳組件uploadify的使用》以及《Web開發中的文件上傳組件uploadify的使用》。

2、數據的導出操作

數據的導出操作相對比較簡單,一般情況下,我們把數據寫入一個固定的Excel表里面,然后提供URL給用戶下載即可。

//導出Excel數據
function ShowExport() {
    var url = "/User/Export";
    var condition = $("#ffSearch").serialize();//獲取條件

    executeExport(url, condition);//執行導出
}

具體的邏輯代碼如下所示

//執行導出操作,輸出文件
function executeExport(url, condition) {
    $.ajax({
        type: "POST",
        url: url,
        data: condition,
        success: function (filePath) {
            var downUrl = '/FileUpload/DownloadFile?file=' + filePath;
            window.location = downUrl;
        }
    });
}

3、附件的查看處理

多數情況下,我們可能需要查看上傳的文件,包括Office文檔、圖片等可以進行預覽的,是在不行,可以提供下載本地打開查看。
我在基于EasyUI的Web開發也介紹了Office的預覽處理:《基于MVC4+EasyUI的Web開發框架經驗總結(8)--實現Office文檔的預覽》,這里我們改進一下即可實現具體的Office預覽和圖片查看功能了。
上篇文件介紹了Office的預覽有兩種途徑,一種是利用微軟Office的預覽地址進行預覽,一種是用控件生成HTML進行預覽,兩種可以結合使用,根據需要進行配置即可。

/// <summary>
/// 根據附件ID,獲取對應查看的視圖URL。
/// 一般規則如果是圖片文件,返回視圖URL地址'/FileUpload/ViewAttach';
/// 如果是Office文件(word、PPT、Excel)等,可以通過微軟的在線查看地址進行查看:'http://view.officeapps.live.com/op/view.aspx?src=',
/// 也可以進行本地生成HTML文件查看。如果是其他文件,可以直接下載地址。
/// </summary>
/// <param name="id">附件的ID</param>
/// <returns></returns>
public ActionResult GetAttachViewUrl(string id)
{
    string viewUrl = "";
    FileUploadInfo info = BLLFactory<FileUpload>.Instance.FindByID(id);
    if (info != null)
    {
        string ext = info.FileExtend.Trim('.').ToLower();
        string filePath = GetFilePath(info);

        bool officeInternetView = false;//是否使用互聯網在線預覽
        string hostName = HttpUtility.UrlPathEncode("http://www.iqidi.com/");//可以配置一下,如果有必要

        if (ext == "xls" || ext == "xlsx" || ext == "doc" || ext == "docx" || ext == "ppt" || ext == "pptx")
        {
            if (officeInternetView)
            {
                //返回一個微軟在線瀏覽Office的地址,需要加上互聯網域名或者公網IP地址
                viewUrl = string.Format("http://view.officeapps.live.com/op/view.aspx?src={0}{1}", hostName, filePath);
            }
            else
            {
                #region 動態第一次生成文件
                //檢查本地Office文件是否存在,如不存在,先生成文件,然后返回路徑供查看
                string webPath = string.Format("/GenerateFiles/Office/{0}.htm", info.ID);
                string generateFilePath = Server.MapPath(webPath);
                if (!FileUtil.FileIsExist(generateFilePath))
                {
                    string templateFile = BLLFactory<FileUpload>.Instance.GetFilePath(info);
                    templateFile = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, templateFile.Replace("\\", "/"));

                    if (ext == "doc" || ext == "docx")
                    {
                        Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);
                        doc.Save(generateFilePath, Aspose.Words.SaveFormat.Html);
                    }
                    else if (ext == "xls" || ext == "xlsx")
                    {
                        Workbook workbook = new Workbook(templateFile);
                        workbook.Save(generateFilePath, SaveFormat.Html);
                    }
                    else if (ext == "ppt" || ext == "pptx")
                    {
                        templateFile = templateFile.Replace("/", "\\");
                        PresentationEx pres = new PresentationEx(templateFile);
                        pres.Save(generateFilePath, Aspose.Slides.Export.SaveFormat.Html);
                    }
                }
                #endregion
                viewUrl = webPath;
            }
        }
        else
        {
            viewUrl = filePath;
        }
    }
    return Content(viewUrl);
}

通過這個后臺處理代碼,我們可以正確知道Office預覽的時候,使用的是哪個URL了。
這樣在前端頁面,我們只需要判斷具體是那種文件,然后進行展示即可了。

if(type =="image") {
    var imgContent = '<img src="'+ viewUrl + '" />';
    $("#divViewFile").html(imgContent);
    $("#file").modal("show");
} else {
    $.ajax({
        type: 'GET',
        url: viewUrl,
        //async: false, //同步
        //dataType: 'json',
        success: function (json) {
            $("#divViewFile").html(json);
            $("#file").modal("show");
        },
        error: function (xhr, status, error) {
            showError("操作失敗" + xhr.responseText); //xhr.responseText
        }
    }); 
}

其中的代碼

$("#file").modal("show");

是我們調用全局對話框,用來展示具體的內容的,效果如下所示。


word文檔預覽效果如下所示:



或者我們查看圖片文件的時候,可以獲得界面效果如下所示:




以上就是 數據的導入、導出及附件的查看處理的介紹內容,希望對大家學習有幫助。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容