本方法缺点:数据量有一定的限制,若列数据过多,则只能导入2000条左右。此方法必须对表格中的列进行类声明。
1.get:
public virtual async Task<ActionResult> ImportStudentMessage(int page = 1)
{
return View(await db.StudentInforms.GetPagedDataAsyns(new PageDataParameter<StudentInform, Guid>(page: page)));
}
``
2.视图页面
@using (Html.BeginForm("ImportStudentMessage", "StudentInforms", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div form-group>
<div class="row">
<div class="clearfix">
<div class="col-xs-4">
<div class="pull-left">
<input name="file" type="file" class="form-control" accept=".xls,.xlsx" />
</div>
<div class="pull-right">
<input type="submit" value="导入" class="btn btn-success btn-sm" />
@Html.ValidationMessage("file", "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
}
3.post方法
[HttpPost]
//[Authorize]
public virtual ActionResult ImportStudentMessage(string file, bool stopWhenError = false)
{
if (Request.Files.Count > 0)
{
if (Request.Files[0].ContentLength > 0)
{
string contentType = Request.Files[0].ContentType;
Guid fileId = Guid.NewGuid();
string path = Server.MapPath("\\Uploads");
string fileNameWithoutPath = System.IO.Path.GetFileName(Request.Files[0].FileName);
string fileName = fileId.ToString().Replace("-", "") + fileNameWithoutPath;
fileName = System.IO.Path.Combine(path, fileName);
try
{
Request.Files[