引入NPOI 2.1.3.1的包
项目引入
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
控制器方法:
public ActionResult DoDormIdImport()
{
return RedirectToAction("DormIdImport");
}
[HttpPost]
public ActionResult DoDormIdImport(HttpPostedFileBase filebase)
{
HttpPostedFileBase file = Request.Files["files"];
string FileName;
string savePath;
if (file == null || file.ContentLength <= 0)
{
ViewBag.error = "文件不能为空";
TempData["msg"] = ViewBag.error;
return RedirectToAction("DormIdImport");
}
else
{
string filename = Path.GetFileName(file.FileName);
int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
int Maxsize = 10000 * 1024;//定义上传文件的最大空间大小为10M
string FileType = ".xlsx";//定义上传文件的类型字符串
FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
if (!FileType.Contains(fileEx))
{
ViewBag.error = "文件类型不对,只能导入.xlsx格式的文件";
TempData["msg"] = ViewBag.error;
return RedirectToAction("DormIdImport");
}
if (filesize >= Maxsize)
{
ViewBag.error = "上传文件超过10M,不能上传";
TempData["msg"] = ViewBag.error;
return RedirectToAction("DormIdImport");
}
string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/excel/";
savePath = Path.Combine(path, FileName);
file.SaveAs(savePath);
}
IWorkbook workbook = null;
using (FileStream fs = new FileStream(savePath, FileMode.Open,FileAccess.Read, FileShare.ReadWrite))
{
//把xls文件读入workbook变量里,之后就可以关闭了
workbook = new XSSFWorkbook(fs);
}
ISheet sheet = workbook.GetSheet("Sheet1");
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
DataTable dt = new DataTable();
rows.MoveNext();
IRow row = (XSSFRow)rows.Current;
for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
{
//dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());
//将第一列作为列表头
dt.Columns.Add(row.GetCell(j).ToString());
}
while (rows.MoveNext())
{
row = (XSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = 0; i < row.LastCellNum; i++)
{
NPOI.SS.UserModel.ICell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
else
{
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}
int affect = 0;
using (TransactionScope transaction = new TransactionScope())
{
IDormManager dm = new DormManager();
foreach (DataRow dr in dt.Rows)
{
affect+=dm.UpdateLockByDorm(dr["number"].ToString(),dr["lockId"].ToString());
}
transaction.Complete();
}
ViewBag.error = "成功导入" + affect + "条";
TempData["msg"] = ViewBag.error;
return RedirectToAction("DormIdImport");
}
//提供模板下载
public FileResult GetFile()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/excel/";
string fileName = "锁IdExcel模板.xlsx";
return File(path + fileName, "text/plain", fileName);
}
页面
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DormIdImport</title>
</head>
<body>
<div>
@using (Html.BeginForm("DoDormIdImport", "Dorm", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h2>
Excel信息导入
</h2>
<div>
<fieldset id="myfieldset">
<legend>excel模版格式 </legend><font color="red">导入Execl的模板格式如下,若模板格式不正确,则相应的Execl不能导入!</font><br />
<p style="color: Red; text-align: center;">@Html.ActionLink("下载模版", "GetFile")</p>
</fieldset>
</div>
<div style="margin-top: 20px;">
<fieldset id="myfieldset1">
<legend>Excel批量信息导入</legend>
<p>
选择文件:<input id="FileUpload" type="file" name="files" style="width: 250px; height: 24px;
background: White" class="easyui-validatebox" />
</p>
<p>
<input id="btnImport" type="submit" value="导入" style="width: 60px; height: 28px;" />
</p>
<p style="color: Red; text-align: center;">@ViewBag.msg</p>
</fieldset>
</div>
}
</div>
</body>
</html>