Asp.net MVC批量导入execel文件

最终效果图1、界面代码如下:

<div class="page-content">
    <div class="page-header col-xs-12 searchdiv">
        <div class="row">
            <div class="form-inline">
                <div style="width:50px;height:60px;float:left;background-color:darkgray;font-size:large;padding-left:5px;border-radius:5px;">说明</div>
                <div style="width:796px;height:60px;float:left;padding-left:10px;padding-top:10px;background-color:#EEE;border-radius:5px;">
                    说明
                </div>

            </div>
        </div>
    </div>
    <div class="page-content col-xs-12" style="background-color:#FFF;border-radius:5px;">
        <div class="form-group">
            <form id="addForm" action="" enctype="multipart/form-data">
                <input type="hidden" name="ptype" value="6" />
                <input type="hidden" name="pname" value="识别名" />
                <input type="hidden" name="folder" value="" />
                <div class="col-xs-10">
                    <div class="col-sm-6">
                        <input type="file" id="id-input-file" name="file" />
                    </div>
                    <div class="col-sm-6">
                        <a id="downLoadTemplateId" class="btn btn-info btn-minier btn-success" style="line-height: 23px" onclick="dload()">
                            <i class="ace-icon fa fa-download"></i>模版下载
                        </a>
                    </div>
                </div>
                <div class="form-group row" id="fileDiv">
                    <input name="fileName" id="filename" type="hidden">
                    <input name="fileUrl" id="fileurl" type="hidden">
                    <input name="fileSize" id="filesize" type="hidden">
                </div>
                <div class="btn-group" style="margin:0px;padding:0px;left:50%">
                    <div class="col-sm-6">
                        <input style="padding-right:5px;" id="btnSave" class="btn  btn-info btn-bold" type="button" value="提交" />
                    </div>
                    <div class="col-sm-6">
                        <input style="padding-left:5px;" id="btnClear" class="btn  btn-danger btn-bold" type="button" value="重置" />
                    </div>
                </div>
            </form>
        </div>
        <hr />
        <div class="row">
            <div class="col-xs-12">
                <div>错误/重复数据列表</div>
                <table class="wintable  table-bordered" width="100%" border="0" cellspacing="0" cellpadding="0" style="border-collapse: collapse;">
                    <thead>
                        <tr>
                            <th>字段</th>
                        </tr>
                    </thead>
                    <tbody id="J_TbData">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
    function dload() {
        var blobUrl = '/控制器/DownLoadXls';
        const a = document.createElement('a');
        a.style.display = 'none';
        a.download = '1.xlsx';
        a.href = blobUrl;
        a.click();
    }
    $('#id-input-file').ace_file_input({
        no_file: '没有选择文件',
        btn_choose: '选择',
        btn_change: '更改',
        droppable: false,
        onchange: null,
        thumbnail: false, //| true | large
        droppable: false,
        allowExt: ['xls', 'xlsx'],    //该属性只是对文件后缀的控制
        before_change: function (files, dropped) {
            //选择文件 展示之前的事件
            //return true 保留当前文件; return false 不保留文件;return -1 重置文件框
            //需要同步等待返回结果
            // uploadjs.upload('addForm', setFileUrl, 'id-input-file', "");
            var formData = new FormData($("#addForm")[0]);
            $.ajax({
                url: '/FileUpload/Upload',  //处理请求
                type: 'POST',
                async: true,
                //Ajax事件
                success: function (data, status) {
                    if (status =='success') {
                        var result = data.split('|');
                        $('#filename').val(result[0]);
                        $('#fileurl').val(result[1]);
                        $('#filesize').val(result[2]);
                    }
                },
                error: function (data, status) {
                    layer.msg(data.Message, {
                        time: 3000
                    });
                },
                // Form数据
                data: formData,
                //类型选项
                cache: false,
                contentType: false,
                processData: false
            });
            return true;
        }
    }).on('file.error.ace', function (event, info) {
        nsDialog.jAlert("请上传excel格式文件", "提示");
    });
    $('#btnSave').click(function () {
        var data = $('#addForm').serializeJson();
        if (data.fileUrl.length == 0) {
            swal({
                title: "提示",
                text: "请上传excel格式文件",
                type: "warning",
            });
            return;
        }
        data.a = '方法名';
        data.c = '控制器名';
        //SaveData(data);
        $.post("/api/地址", data, function (jdata) {
            if (jdata != null && jdata.m == "0") {
                //传递结果给列表页
                var hs = $("#handle_status", window.parent.window.frames["mainFrame"].document).val(jdata.m);
                hs.val(jdata.m);
                hs.attr('msg', jdata.msg);
                swal({
                    title: "处理结果",
                    text: jdata.msg,
                    type: "success",
                }, function () {
                    //清空所有的子节点
                    $("#J_TbData").empty();
                    if (jdata != null && jdata.data != null) {
                        for (var i = 0; i < jdata.data.length; i++) {
                            //动态创建一个tr行标签,并且转换成jQuery对象
                            var $trTemp = $("<tr></tr>");

                            //往行里面追加 td单元格
                            $trTemp.append("<td>" + jdata.data[i].字段 + "</td>");//字段
                            $trTemp.appendTo("#J_TbData");
                        }
                    }
                });

            } else {
                swal({
                    title: "处理结果",
                    text: jdata.msg,
                    type: "warning",
                });
            }
        });
        return false;
    })
    //重置
    $('#btnClear').click(function () {
        $("#filename").attr("value", "");
        $("#fileurl").attr("value", "");
        $("#filesize").attr("value", "");
        $('.remove').click();
    })
    $(".remove").bind("click", function () {
        $("#filename").attr("value", "");
        $("#fileurl").attr("value", "");
        $("#filesize").attr("value", "");
        $('.remove').click();
    });
</script>

 2、下载模板方法代码如下:DownLoadXls

  /// 下载模板xls
        /// </summary>
        /// <param name="xdsj"></param>
        /// <returns></returns>
        public FileResult DownLoadXls()
        {
            var path = Server.MapPath("~/Content/***模板.xlsx");

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            //Read all bytes into an array from the specified file.
            int nBytes = (int)fs.Length;//计算流的长度
            byte[] byteArray = new byte[nBytes];//初始化用于MemoryStream的Buffer
            int nBytesRead = fs.Read(byteArray, 0, nBytes);//将File里的内容一次性的全部读到byteArray中去
            MemoryStream ms = new MemoryStream(byteArray);//初始化MemoryStream,并将Buffer指向FileStream的读取结果数组
            return File(ms, "application/vnd.ms-excel", "***模板.xlsx");
        }

3、上传excel文件方法


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Upload(string ptype, string pname, string folder)
        {
            

            if (ControllerContext.HttpContext.Request != null && ControllerContext.HttpContext.Request.Files.Count > 0)
            {
                
                    ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
                    ControllerContext.HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
                    ControllerContext.HttpContext.Response.Charset = "UTF-8";
                    //源图片路径
                    HttpPostedFileBase fileData = ControllerContext.HttpContext.Request.Files[0];
               //根据业务保存文件到指定位置
             }
}

4、根据上传文件名解析文件内容批量导入代码如下

 /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="newModel"></param>
        /// <returns></returns>
        private JsonResponse SaveLeadIn(S_EXAMRESLEADIN_MNKS newModel)
        {
            JsonResponse jr = new JsonResponse();
            if (string.IsNullOrEmpty(newModel.fileName))
            {
                jr.m = -1;
                jr.msg = "请先选择文件"; return jr;
            }
            string root = HttpContext.Current.Server.MapPath(newModel.fileUrl);
       }


 public class S_EXAMRESLEADIN_MNKS
    {
        /// <summary>
        /// 文件名
        /// </summary>
        public string fileName { get; set; }
        /// <summary>
        /// 文件路径
        /// </summary>
        public string fileUrl { get; set; }
        /// <summary>
        /// 文件大小
        /// </summary>
        public string fileSize { get; set; }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值