你的控制器可以是这样的:
public ActionResult Import(System.Web.HttpPostedFileBase uploadFile)
{
if (uploadFile != null)
{
if (uploadFile.ContentLength > 0)
{
var fileExtension = Path.GetExtension(uploadFile.FileName);
if (fileExtension.ToLower().Equals(".xlsx"))
{
BinaryReader b = new BinaryReader(uploadFile.InputStream);
int count = uploadFile.ContentLength;
byte[] binData = b.ReadBytes(count);
using (MemoryStream stream = new MemoryStream(binData))
{
//call the service layer to read the data from stream
}
}
}
}
}
而你的服务层就是你已经想出来的,用NPOI来读取。
根据您从 excel 文件中读取的数据,您的模型可能是这样的:
public class Product
{
public int ProductID {get; set;}
public string Name {get; set;}
public decimal Price {get; set;}
}
在数据库中,您可以有一个存储过程,它可以使用用户定义的表类型来获取多行数据。读取服务层中的数据后,您可以从存储库中调用此存储过程。
最后在视图中,你可以有一个带有文件上传对话框的表单,并传递用户上传的文件。调用控制器的 Javascript 可能是这样的:
function x () {
var inputdata = null;
var form = $('#__ImportFileForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var fd = new FormData();
fd.append("__RequestVerificationToken", token);
fd.append("uploadFile", $("#uploadFile")[0].files[0]);
inputdata = fd;
inputdata.skipAjaxPrefilter = true;
$.ajax({
type: "Post",
url: url,
data: inputdata,
processData: false,
contentType: false,
traditional: true,
async: true,
success: function(data) { //do what you want },
error: function(data, ajaxOptions, thrownError) { //do what you want }
});
}
希望这能回答你所有的问题!