博主用的是npoi2.0.1,支持.xls也支持.xlsx
直接上代码吧。
<table class="table table-bordered table-striped"> <thead> <tr> <th>Shape</th> <th>Pcs</th> <th>Sizw</th> <th>Size Range</th> <th>Color</th> <th>Clarity</th> <th>Rap-Price</th> <th>Cut</th> <th>POL</th> <th>SYM</th> <th>H&A</th> <th>FL</th> <th>Diam/LxW</th> <th>Dep%</th> <th>Tab%</th> <th>Rap%</th> <th>LAB1</th> <th>CersNo</th> <th>LAB2</th> <th>CersNo</th> <th>Price/ct¥</th> </tr> </thead> <tbody id="td"> </tbody> </table>
之后用了jquery.form.js
function uploadFile() { var options = { type: "post", enctype: "multipart/form-data", url: "UploadExcel", success: function (data) { if (data != null) { $("#td").append(data); $("#uploadData").css("display", "block"); } else if (data == 0) { layer.msg('文档加载失败!', { icon: 5 }, function () { $("#uploadData").css("display", "none"); }); } else if (data == -1) { layer.msg('数据库连接失败!', { icon: 5 }, function () { $("#uploadData").css("display", "none"); }); } else { layer.msg('未知错误!', { icon: 5 }, function () { $("#uploadData").css("display", "none"); }); } }, processData: true, global: true }; $("#form").ajaxSubmit(options); }
跟着是动作方法
public ActionResult UploadExcel() { string rtn = "1"; if (Request.Files.Count > 0) { HttpPostedFileBase file = Request.Files["File"]; string newFile = Server.MapPath("~/Areas/Admin/UploadFile/StockImprot/") + DateTime.Now.ToString("yyyyMMddHHmmss") + file.FileName; while (System.IO.File.Exists(newFile)) { newFile = Server.MapPath("~/Areas/Admin/UploadFile/StockImprot/") + DateTime.Now.ToString("yyyyMMddHHmmss") + file.FileName; } file.SaveAs(newFile); DataTable ds = ExcelHelper.GetDataTable(newFile); if (ds != null) { if (ds.Rows != null) { ViewData["datatable"] = ds; return PartialView("_PartialDataTable"); //注意这里返回是的局部视图哦 } } else { rtn = "0"; //文档加载失败 } } else { rtn = "-1"; } return Content(rtn); }
局部视图的代码
@if (ViewData["datatable"] != null) { System.Data.DataTable dt = ViewData["datatable"] as System.Data.DataTable; foreach (System.Data.DataRow dr in dt.Rows) { <tr> <td>@dr[0].ToString()</td> <td>@dr[1].ToString()</td> <td>@dr[2].ToString()</td> <td>@dr[3].ToString()</td> <td>@dr[4].ToString()</td> <td>@dr[5].ToString()</td> <td>@dr[6].ToString()</td> <td>@dr[7].ToString()</td> <td>@dr[8].ToString()</td> <td>@dr[9].ToString()</td> <td>@dr[10].ToString()</td> <td>@dr[11].ToString()</td> <td>@dr[12].ToString()</td> <td>@dr[13].ToString()</td> <td>@dr[14].ToString()</td> <td>@dr[15].ToString()</td> <td>@dr[16].ToString()</td> <td>@dr[17].ToString()</td> <td>@dr[18].ToString()</td> <td>@dr[19].ToString()</td> <td>@dr[20].ToString()</td> </tr> } }
最后上一张效果图
---------------------------------------------------------------------------------------------------------
转载请记得说明作者和出处哦-.-
作者:KingDuDu
原文出处:https://www.cnblogs.com/kingdudu/articles/4745151.html
---------------------------------------------------------------------------------------------------------