@{
    Layout = "~/Views/_LayoutBase.cshtml";
}
@section css{
    <link href="/Content/uploadify/uploadify.css" rel="stylesheet" />

}
<div class="easyui-panel" style="margin-bottom: 10px; padding: 5px;">
    <span>商户名称:</span>
    <input class="easyui-textbox" id="storename">

    <a href="#" class="easyui-linkbutton" id="search" data-options="iconCls:'icon-search'">查 询</a>
    <a href="#" class="easyui-linkbutton" id="reload" data-options="iconCls:'icon-reload'">清 空</a>
    <button type="button" class="easyui-linkbutton" id="btnImport" data-options="">导入商户数据</button>
</div>
<div id="datalist">
    <table id="grid" class="easyui-datagrid"></table>
</div>
<!--导入商户信息-->
<div id="importProductWindow" class="easyui-window" title="导入商户信息" data-options="iconCls:'icon-save',closed:true" style="width: 520px; height: 200px; padding: 5px;">
    <div class="easyui-layout" data-options="fit:true">
        <div style="padding: 10px;">
            <form id="importProudctForm" enctype="multipart/form-data">
                <table>
                    @*<tr>
                        <td>选择门店:</td>
                        <td>
                            <select class="easyui-combobox" id="impStore" style="width:250px">
                                @foreach (var item in ViewBag.StoreList)
                                {
                                    <option value="@item.PStoreId">@item.FName</option>
                                }
                            </select>
                        </td>
                    </tr>*@
                    <tr>
                        <td>选择 Excel(.xls 或 .xlsx) 文件:</td>
                        <td> <input type="file" id="importProductFile" name="importProductFile" /> </td>
                    </tr>
                    <tr>
                        <td>商户信息导入 Excel 模板</td>
                        <td colspan="3">
                            <a href="/Content/商户导入模板.xls">下载</a>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="4" style="text-align:center;">
                            <a class="easyui-linkbutton" id="btnImportProductOk" data-options="iconCls:'icon-ok'" href="javascript:void(0)" style="width: 80px">确 定</a>
                            <a class="easyui-linkbutton" id="btnImportProductCancel" data-options="iconCls:'icon-cancel'" href="javascript:void(0)" style="width: 80px">取 消</a>
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
</div>
<div id="detail" class="easyui-window" title="修改" data-options="iconCls:'icon-save',closed:true,fit:true,modal:true" style="width:100%;height: 100%; padding: 5px;">
    <div class="easyui-layout" data-options="fit:true" style="height: 1070px;overflow:auto;">
        <form id="ff" action="/About/SaveAbout" method="post">
            <table>
                <tr>
                    <td style="width:70px;">
                        ID:
                    </td>
                    <td>
                        <input class="easyui-textbox" style="width:400px;" type="text" id="pid" name="pid" />
                    </td>
                </tr>
                <tr>
                    <td style="width:70px;">
                        商户名称:
                    </td>
                    <td>
                        <input class="easyui-textbox" style="width:400px;" type="text" id="kstoreName" name="kstoreName" />
                    </td>
                </tr>
                <tr>
                    <td style="width:70px;">
                        商户编号:
                    </td>
                    <td>
                        <input class="easyui-textbox" style="width:400px;" type="text" id="kstorenum" name="kstorenum" />
                    </td>
                </tr>
                @*<tr>
                        <td style="width:70px;">
                            是否启用:
                        </td>
                        <td>
                            <select class="easyui-combobox" style="width:120px" id="state" name="state">
                                <option value="1">启用</option>
                                <option value="2">禁用</option>
                            </select>
                        </td>
                    </tr>*@
            </table>
            <input type="hidden" id="hiddenId" name="hiddenId" />
        </form>
        <div data-options="region:'south',border:false" style="text-align: center; padding: 5px 0 0;">
            <a class="easyui-linkbutton" id="btnOk" data-options="iconCls:'icon-ok'" href="javascript:void(0)" style="width: 80px">确 定</a>
            <a class="easyui-linkbutton" id="btnCancel" data-options="iconCls:'icon-cancel'" href="javascript:void(0)" style="width: 80px">取 消</a>
        </div>
    </div>
</div>

@section javascript{
    <script src="/Content/uploadify/jquery.uploadify.min.js"></script>
    <script type="text/javascript">
        $("#btnImportProductOk").click(function () {
            var file = $("#importProductFile")[0];
            if (!file) {
                msgShow("系统提示", "请选择要上传的 Excel 文件!", "warning");
                return;
            }
            var formData = new FormData();
            formData.append("file", file.files[0]);
            $.ajax({
                cache: false,
                type: "post",
                processData: false,
                contentType: false,
                data: formData,
                url: "/User/ImportStoreExcel",
                //url: "/Product/ImportExcelForXHLG",
                beforeSend: ajaxLoading,
                success: function (data) {
                    ajaxLoadEnd();
                    if (data.Status == 1) {
                        msgShow("系统提示", "上传成功!", "info");
                        $("#importProductForm")[0].reset();
                        $("#importProductWindow").window('close');
                        $("#grid").datagrid("reload");
                    } else {
                        msgShow("系统提示", data.Msg, "warning");
                    }
                },
                error: function (request) {
                    msgShow("系统提示", "服务器端异常!", "warning");
                }
            });
        });
        $("#btnImportProductCancel").click(function () {
            $("#importProductWindow").window('close');
            $("#importProductForm")[0].reset();
        });
        $("#btnImport").click(function () {
            $("#importProductWindow").window('open');
        });
        var queryData = {};
        queryData["kstorename"] = "";
        $("#search").click(function search() {
            queryData["kstorename"] = $("#storename").textbox("getValue");
            InitGrid();
        });
        $("#reload").click(function () {
            $("#storename").textbox("setValue", '');
        });
        //var ue = UE.getEditor('editor');
        var tool = [
            {
                id: 'btnEdit',
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    EditBind(0);
                },
            }, {
                id: 'btnEdit',
                text: '修改',
                iconCls: 'icon-edit',
                handler: function () {
                    EditBind(1);
                },
            }, {
                id: 'btnDelete',
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    var row = $('#grid').datagrid('getSelected');
                    if (row) {
                        $.messager.confirm('删除类型', '你确认要删除该问题吗 ?', function (r) {
                            if (r) {
                                var url = "/User/DeleteStoreMember";
                                var pars = {};
                                pars["pid"] = row.PID;

                                $.ajax({
                                    type: "post",
                                    url: url,
                                    async: false,
                                    dataType: "json",
                                    data: pars,
                                    success: function (data) {
                                        if (data) {
                                            $("#grid").datagrid("reload");
                                        } else {
                                            msgShow("系统提示", "修改失败!", "warning");
                                        }
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        $.messager.alert('登录超时', '操作失败,请重新登录!', "error", function (r) {
                                            parent.location.reload();
                                        });

                                    }
                                });
                            }
                        });
                    } else {
                        msgShow("系统提示", "请选择用户!", "warning");
                    }
                },
            }, {
                id: 'btnReload',
                text: '刷新',
                iconCls: 'icon-reload',
                handler: function () {
                    //实现刷新栏目中的数据
                    $("#grid").datagrid("reload");
                },
            }
        ];
        function InitGrid() {
            $('#grid').datagrid({   //定位到Table标签,Table标签的ID是grid
                url: '/User/GetTStoreMember',   //指向后台的Action来获取当前用户的信息的Json格式的数据
                //title: '常见问题及回答',
                iconCls: 'icon-view',
                iconCls: 'icon-view',
                height: 650,
                width: function () { return document.body.clientWidth * 0.9 },//自动宽度
                //nowrap: true,
                loadMsg: "正在加载数据中...",
                //autoRowHeight: false,
                striped: true,
                collapsible: true,
                pagination: true,
                pageSize: 20,
                pageList: [20, 50, 100, 200],
                rownumbers: true,
                sortOrder: 'asc',
                remoteSort: false,
                singleSelect: true,
                fit: false,
                idField: 'PID',
                queryParams: queryData,  //异步查询的参数
                columns: [[
                    { title: 'ID', field: 'PID', width: 120, sortable: false },
                    { title: '商户名称', field: 'KStoreName', width: 120, sortable: false },
                    { title: '商户编号', field: 'KStoreNum', width: 180, sortable: false },
                    //{ title: '排序', field: 'FSort', width: 120, sortable: false },
                    //{
                    //    title: '状态', field: 'FState', width: 120, sortable: false, formatter: function (value, row, index) {
                    //        if (value == 1)
                    //            return "启用";
                    //        return "禁用";
                    //    }
                    //},
                    //{ title: '创建时间', field: 'FTime', width: 150, sortable: false }
                ]],
                toolbar: tool,
                onDblClickRow: function (rowIndex, rowData) {
                    EditBind(1);
                },
                onLoadSuccess: function (data) {
                    if (data.total == 0) {
                        //添加一个新数据行,第一列的值为你需要的提示信息,然后将其他列合并到第一列来,注意修改colspan参数为你columns配置的总列数
                        $(".datagrid-view2 .datagrid-body").append("<div class='divNone'><i></i><span>没有符合条件的数据</span></div>");
                        //隐藏分页导航条,这个需要熟悉datagrid的html结构,直接用jquery操作DOM对象,easyui datagrid没有提供相关方法隐藏导航条
                        $(this).closest('div.datagrid-wrap').find('div.datagrid-pager').hide();
                    }
                    //如果通过调用reload方法重新加载数据有数据时显示出分页导航容器
                    else {
                        $(".divNone").remove();
                        $(this).closest('div.datagrid-wrap').find('div.datagrid-pager').show();
                    }
                }
            })
        }

        function EditBind(type) {
            //这里等于0是添加,其他是修改
            if (type == 0) {
                $('#hiddenId').val(0);
                $('#pid').textbox('setValue', "");
                $('#state').combobox('setValue', "1");
                $('#kstoreName').textbox('setValue', "");
                $('#kstorenum').textbox('setValue', "");
            } else {
                var row = $('#grid').datagrid('getSelected');
                if (row) {
                    $('#hiddenId').val(row.PID);
                    $('#pid').textbox('setValue', row.PID);
                    $('#kstoreName').textbox('setValue', row.KStoreName);
                    $('#kstorenum').textbox('setValue', row.KStoreNum);
                    $('#answer').textbox('setValue', row.FContent);
                }
            }
            $('#detail').window('open');
        }
        $(function () {
            InitGrid();

            $("#btnOk").click(function () {
                //$("#ff").submit();
                var url = "/User/SaveStoreMember";
                var pars = $("#ff").serialize();
                $.ajax({
                    type: "post",
                    url: url,
                    async: false,
                    dataType: "json",
                    data: pars,
                    success: function (data) {
                        if (data > 0) {
                            $('#detail').window('close');
                            $("#grid").datagrid("reload");
                        } else {
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('登录超时', '操作失败,请重新登录!', "error", function (r) {
                            parent.location.reload();
                        });
                    }
                });
            });

            $("#btnCancel").click(function () {
                $('#detail').window('close');
            });

        });
    </script>
}

下面是后端代码

 

public ActionResult ApplyMenber()
        {
            return View();
        }

        public ActionResult GetTStoreMember()
        {
            using (YXXEntities entity = new YXXEntities())
            {
                var pageindex = int.Parse(Request.Form["page"]);
                var pagesize = int.Parse(Request.Form["rows"]);
                var kstoreName = Request.Form["kstoreName"];
                int count = 0;
                List<TStoreMember> storeMembers = new List<TStoreMember>();
                storeMembers = entity.TStoreMember.Where(p => p.KStoreState == true).OrderBy(p => p.PID)
                    .Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
                if (!string.IsNullOrEmpty(kstoreName))
                {
                    storeMembers = storeMembers.Where(p => p.KStoreName.Contains(kstoreName)).ToList();
                }

                count = entity.TStoreMember.Count(p => p.PID > 0);
                var jsonMap = new Dictionary<string, object>();
                jsonMap.Add("total", count);
                jsonMap.Add("rows", storeMembers);
                return Content(JsonConvert.SerializeObject(jsonMap));
            }
        }

        [ValidateInput(false)]
        public ActionResult SaveStoreMember()
        {
            var pid = Convert.ToInt32(Request.Form["pid"]);
            var kstoreName = Request.Form["kstoreName"];
            var kstorenum = Request.Form["kstorenum"];
            using (YXXEntities entity = new YXXEntities())
            {
                TStoreMember storeMember = entity.TStoreMember.FirstOrDefault(p => p.PID == pid);
                if (storeMember == null)
                {
                    storeMember = new TStoreMember()
                        {PID = pid, KStoreName = kstoreName, KStoreNum = kstorenum, KStoreState = true};
                    entity.TStoreMember.Add(storeMember);
                    entity.SaveChanges();
                    return Content(JsonConvert.SerializeObject(true));
                }
                else
                {
                    storeMember.PID = pid;
                    storeMember.KStoreName = kstoreName;
                    storeMember.KStoreNum = kstorenum;
                    storeMember.KStoreState = true;
                    entity.Entry(storeMember).State = EntityState.Modified;
                    entity.SaveChanges();
                    return Content(JsonConvert.SerializeObject(true));
                }
            }

            return Content("");
        }

        public ActionResult DeleteStoreMember(int pid)
        {
            using (YXXEntities entity = new YXXEntities())
            {
                TStoreMember storeMember = entity.TStoreMember.FirstOrDefault(p => p.PID == pid);
                if (storeMember != null)
                {
                    storeMember.KStoreState = false;
                    entity.Entry(storeMember).State = EntityState.Modified;
                    entity.SaveChanges();
                    return Content(JsonConvert.SerializeObject(true));
                }
                else
                {
                    return Content(JsonConvert.SerializeObject(false));
                }
            }
        }

        public ActionResult ImportStoreExcel(HttpPostedFileWrapper file)
        {
            if (file == null || file.ContentLength == 0)
            {
                return Json(new {Status = 0, Msg = "不允许上传空文件"});
            }

            var ext = Path.GetExtension(file.FileName).ToLower();
            if (ext != ".xlsx" && ext != ".xls")
            {
                return Json(new {Status = 0, Msg = "只支持上传 Excel 文件,文件扩展名为 .xlsx 或 .xls"});
            }
            
            using (var db = new YXXEntities())
            {
                var saveFileName = DateTime.Now.ToString("yyyyMMddHHmmss_") + file.FileName;
                var uploadPath = Server.MapPath($@"\YXXServer\storemember\{saveFileName}");
                file.SaveAs(uploadPath);
                using (var fs = new FileStream(uploadPath, FileMode.Open, FileAccess.Read))
                {
                    IWorkbook workbook = null;
                    if (saveFileName.IndexOf(".xlsx") > 0) // 2007版本
                        workbook = new XSSFWorkbook(fs);
                    else if (saveFileName.IndexOf(".xls") > 0) // 2003版本
                        workbook = new HSSFWorkbook(fs);
                    var sheet = workbook.GetSheetAt(0);
                    if (sheet != null)
                    {
                        int i;//存储出错行
                        try
                        {
                            int rowCount = sheet.LastRowNum;
                            for (i = sheet.FirstRowNum + 1; i <= rowCount; ++i)//从第二行开始取数据
                            {
                                try
                                {
                                    var row = sheet.GetRow(i);
                                    if (row.GetCell(0) != null)
                                    {
                                        row.GetCell(0).SetCellType(CellType.String);
                                    }
                                    if (row.GetCell(2) != null)
                                    {
                                        row.GetCell(2).SetCellType(CellType.String);
                                    }
                                    if (row == null || row.GetCell(0) == null || row.GetCell(0).StringCellValue == "") break; //没有数据的行默认是文件结束
                                    string SPID = row.GetCell(0).StringCellValue;
                                    int PID = Convert.ToInt32(SPID);
                                    string KStoreName = row.GetCell(1).StringCellValue;
                                    string KStoreNum = row.GetCell(2).StringCellValue;
                                    if(db.TStoreMember.Count(p=>p.KStoreName==KStoreName&&p.KStoreNum==KStoreNum&&p.KStoreState==true)>0)continue;
                                    TStoreMember tstoremenber =new TStoreMember();
                                    tstoremenber.PID = PID;
                                    tstoremenber.KStoreName = KStoreName;
                                    tstoremenber.KStoreNum = KStoreNum;
                                    tstoremenber.KStoreState = true;
                                    db.TStoreMember.Add(tstoremenber);
                                    db.SaveChanges();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                    throw;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            System.IO.File.Delete(uploadPath);
                            return Json(new { Status = 0, Msg = "导入 Excel 文件时出错,请坚持文件内容格式是否与模板一致!" });
                        }
                        if (System.IO.File.Exists(uploadPath))
                        {
                            System.IO.File.Delete(uploadPath);
                        }
                        return Json(new { Status = 1, Msg = "" });
                    }
                }
            }


            return Content("ok");

            
    }