前台页面
@using (Html.BeginForm("ExcelCheck", "ExcelImportAndExport", FormMethod.Post, new { @class = "form-horizontal", @role = "form", @id = "uploadForm", @enctype = "multipart/form-data" }))
<input id="FileUpload" type="file" class="form-control no-padding-left" name="FileUpload">
//导入
$("#FileUpload").on("change", function (e) {
var options = {
url: '@Url.Action("ExcelCheck", "ExcelImportAndExport")', (与表单方法一致)
type: "POST",
dataType: "json",
success: function (msg) {
VehNos = msg.Nos;
var valye;
var arr = msg.Nos.split(",");
$.each(arr, function (index, args) {
if (index == 0) {
valye = args + "\r\n"
}
else {
valye = valye + args + "\r\n"
}
})
$("#vincode").val("导入序列号:" + msg.Count + "\r\n" + valye);
SumPro = msg.Count;
var value = $('#proselect').select2("val") != "" ? ($('#proselect').select2("val").split("-")[1]) : "0";
var pri = $('#monthselect').select2("val") != "" ? ($('#monthselect').select2("val")) : "0";
Price = Number(Number(value) * Number(pri) * SumPro).toFixed(2);
$("#spanmoney").html(Price);
}
}
$("#uploadForm").ajaxSubmit(options); //form表单提交
})
后台导出
[HttpPost]
public ActionResult ExcelCheck(BatchQueryModel batchmodel)
{
IList<string> Nos = null;
var npoi = new Npoi();
//FileStream fileStream = File.Open(fileName, FileMode.Open);
Stream fileStream = batchmodel.FileStream;
IList<string> items = npoi.Load(fileStream, "");//从excel 中获取所有的数据
fileStream.Close();
string nos = "";
if (items.Count > 0)
{
for (int i = 0; i < items.Count; i++)
{
if (i == 0)
{
nos = items[i] ;
}
else
{
nos = nos + "," + items[i] ;
}
}
}
string ret = "{\"Count\":\"" + items.Count + "\",\"Nos\":\"" + nos + "\"}";
return Content(ret, "application/json");
}
类:
namespace CatPay.Web.Models
{
[ModelBinder(typeof(BatchQuertModelBinder))]
[Serializable]
public class BatchQueryModel
{
public Stream FileStream { get; set; }
public string ExcelType { get; set; }
}
public class BatchQuertModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
var model = new BatchQueryModel();
HttpPostedFileBase postFile = request.Files["FileUpload"]; //Request上传的file数据
if (postFile != null)
{
model.FileStream = postFile.InputStream;
model.ExcelType = postFile.FileName.EndsWith(".xlsx") ? "xlsx" : "xls";
}
return model;
}
}
}