分别用到6个类库,分别是:
NPOI.dll
NPOI.OOXML.dll
NPOI.OpenXml4Net.dll
NPOI.OpenXmlFormats.dll
NPOI.XML
ICSharpCode.SharpZipLib.dll
类目在demo包里面,目录:NPOIDemo / NPOIDemoWeb / NPOIDemoWeb / NPOIDLL
完整demo地址:https://download.csdn.net/download/qq_23663693/12370014
项目页面代码如下:
@model IEnumerable<NPOIDemoWeb.Model.ModelStudent>
@{
ViewBag.Title = "About";
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script type="text/javascript">
$(function () {
//当选择上传文件改变时
$("#upLoadFile").change(function () {
var val = $("#upLoadFile").val().substr($("#upLoadFile").val().lastIndexOf(".") + 1, 4);
if (val.toLowerCase() == "xls" || val.toLowerCase() == "xlsx") {
$("#submitBtn").click();//form表单post提交
} else {
alert('上传文件格式不正确,只能上传“.xls;.xlsx”格式文件!');
}
});
});
//
function NowImport() {
alert('将数据保存到自己的数据库即可!')
}
</script>
}
@using (Html.BeginForm("About", "Home", new { classId = @ViewData["ClassId"]}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="container" style="width: 100%;margin:20px auto 0px auto;padding-left: 40px;">
<div>
<font class="fontClass">请选择.xls格式文件:</font>
<input type="file" style="width: 260px;" id="upLoadFile" name="upLoadFile" accept=".xls,.xlsx" />
<input type="submit" id="submitBtn" name="submitBtn" style="display: none" />
</div>
</div>
<div id="result" style="width: 90%; height: 330px; border: 1px solid #DDDDDD;margin-top: 20px;margin:20px auto 0px auto; text-align: center;overflow-y: auto;overflow-x:hidden">
<div id="studentList" style="width: 100%;">
@{
if (Model != null)
{
<div style="width: 100%;height: 40px;line-height:40px; border-bottom:1px solid #d0cfcf;background-color: #d0cfcf;font-weight: bold ">
<div class="head_Td" style="width:100px;float:left;">学号</div>
<div class="head_Td" style="width:100px;float:left;">手机号码</div>
<div class="head_Td" style="width:100px;float:left;">姓名</div>
<div class="head_Td" style="width:150px;float:left;">身份证号</div>
<div class="head_Td" style="width:100px;float:left;">性别</div>
</div>
<div id="bodyList" style="width: 100%;height: auto;">
@for (int i = 0; i < Model.Count(); i++)
{
<div class="body_Tr" style="width: 100%;height: 40px;line-height:40px;">
<div class="body_Td" style="width:100px;float:left;" title="@Model.ToList()[i].xuehao">@Model.ToList()[i].xuehao</div>
<div class="body_Td" style="width:100px;float:left;" title="@Model.ToList()[i].iphone">@Model.ToList()[i].iphone</div>
<div class="body_Td" style="width:100px;float:left;" title="@Model.ToList()[i].name">@Model.ToList()[i].name</div>
<div class="body_Td" style="width:150px;float:left;" title="@Model.ToList()[i].cardId">@Model.ToList()[i].cardId</div>
<div class="body_Td" style="width:100px;float:left;">
@if (Model.ToList()[i].sex == 1)
{<span>女</span>}
else
{ <span>男</span>}
</div>
</div>
}
</div>
}
}
</div>
</div>
}
<div class="dRowsStudent" style="text-align:center;margin-top:10px;">
<div class="dFieldStudent">
<input type="button" id="btnFileSave" class="k-button k-primary" value="立即导入" οnclick="NowImport()"/>
</div>
</div>
Controllers 代码如下:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOIDemoWeb.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NPOIDemoWeb.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
/// <summary>
/// excel导入学生名单
/// </summary>
/// <param name="classId"></param>
/// <returns></returns>
public ActionResult About(string classId)
{
if (Request.HttpMethod != "POST")
{
ViewData["ClassId"] = classId;
return View();
}
else
{
ViewData["ClassId"] = classId; //为了错误返回
HttpFileCollectionBase files = Request.Files; //客户端上载的文件
try
{
if (files.Count > 0)
{
HttpPostedFileBase postedFile = files[0];
string fileExt = postedFile.FileName.ToLower().Substring(postedFile.FileName.LastIndexOf(".")); //文件扩展名,不含“.”
MemoryStream mfile = new MemoryStream();
postedFile.InputStream.CopyTo(mfile);
mfile.Position = 0;//解决XSSFWorkbook: EOF in header的问题
IWorkbook workbook = null;
if (fileExt == ".xls")
{
workbook = new HSSFWorkbook(mfile);//.xls后缀的excel文件
}
else if (fileExt == ".xlsx")
{
workbook = new XSSFWorkbook(mfile);//.xlsx后缀的excel文件
}
ISheet sheet = workbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();//选手名单
List<ModelStudent> list = new List<ModelStudent>();
///循环excel
#region 循环excel
rows.MoveNext();//标头
while (rows.MoveNext())//
{
IRow row = (IRow)rows.Current;
object cell1 = row.GetCell(1);
if (cell1 != null)
{
if (Convert.ToString(row.GetCell(0).ToString().Trim()) != "")
{
ModelStudent studentInfo = new ModelStudent();
studentInfo.xuehao = (row.GetCell(0) == null) ? "" : Convert.ToString(row.GetCell(0).ToString().Trim());
studentInfo.iphone = (row.GetCell(1) == null) ? "" : Convert.ToString((row.GetCell(1).ToString().Trim()));
studentInfo.name = (row.GetCell(2) == null) ? "" : Convert.ToString((row.GetCell(2).ToString().Trim()));
studentInfo.cardId = (row.GetCell(3) == null) ? "" : Convert.ToString((row.GetCell(3).ToString().Trim()));
studentInfo.sex = (row.GetCell(4) == null) ? 0 : Convert.ToInt32((row.GetCell(4).ToString().Trim()) == "女" ? 1 : 0);
list.Add(studentInfo);
}
}
}
#endregion
TempData["Student"] = list;
return View("About", list);
}
else
{
return null;
}
}
catch (Exception ex)
{
TempData["code"] = ex.Message;
return View("Contact");
}
}
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Model.ModelStudent 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NPOIDemoWeb.Model
{
public class ModelStudent
{
/// <summary>
/// 学号
/// </summary>
public string xuehao { get; set; }
/// <summary>
/// 手机号
/// </summary>
public string iphone { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string name { get; set; }
/// <summary>
/// 证件号码
/// </summary>
public string cardId { get; set; }
/// <summary>
/// 性别
/// </summary>
public int sex { get; set; }
/// <summary>
}
}