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; }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET MVC导入Excel文件到数据库功能可以通过以下步骤实现: 1. 创建一个控制器和视图来上传Excel文件。 2. 使用第三方库如EPPlus来解析Excel文件并将其转换为数据表。 3. 使用ADO.NET连接到数据库并将数据表中的数据插入到数据库中。 以下是一个示例控制器和视图的代码: 控制器: ``` public class ExcelController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Import(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { string fileName = Path.GetFileName(file.FileName); string fileExtension = Path.GetExtension(fileName); if (fileExtension == ".xls" || fileExtension == ".xlsx") { string filePath = Server.MapPath("~/Content/" + fileName); file.SaveAs(filePath); DataTable dt = ReadExcelFile(filePath); InsertDataIntoDatabase(dt); return RedirectToAction("Index"); } else { ViewBag.Message = "Please upload a valid Excel file."; return View("Index"); } } else { ViewBag.Message = "Please select an Excel file to upload."; return View("Index"); } } private DataTable ReadExcelFile(string filePath) { using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; DataTable dt = new DataTable(); bool hasHeaderRow = true; foreach (var firstRowCell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column]) { dt.Columns.Add(hasHeaderRow ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column)); } int startRow = hasHeaderRow ? 2 : 1; for (int rowNum = startRow; rowNum <= worksheet.Dimension.End.Row; rowNum++) { var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column]; DataRow row = dt.Rows.Add(); foreach (var cell in wsRow) { row[cell.Start.Column - 1] = cell.Text; } } return dt; } } private void InsertDataIntoDatabase(DataTable dt) { string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES (@Column1, @Column2, @Column3)"; foreach (DataRow row in dt.Rows) { command.Parameters.AddWithValue("@Column1", row["Column1"]); command.Parameters.AddWithValue("@Column2", row["Column2"]); command.Parameters.AddWithValue("@Column3", row["Column3"]); command.ExecuteNonQuery(); command.Parameters.Clear(); } } } } ``` 视图: ``` @{ ViewBag.Title = "Import Excel File"; } <h2>Import Excel File</h2> @using (Html.BeginForm("Import", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-group"> <label for="file">Select Excel File:</label> <input type="file" name="file" id="file" /> </div> <button type="submit" class="btn btn-primary">Import</button> <div class="alert alert-danger" role="alert">@ViewBag.Message</div> } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值