在項目中添加對NPOI的引用
視圖部分如下:
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
@Html.ActionLink("導出用戶", "ExportExcel")
<br />
@using (@Html.BeginForm("ImportExcel", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<text>選擇上傳Excel文件:</text>
<input name="file" type="file" id="file" />
<input type="submit" name="Upload" value="批量導入用戶" />
控制器部分:
public class ExcelController : Controller
{
//
// GET: /Excel/
public ActionResult Index()
{
return View();
}
/// <summary>
/// 批量導出Excel
/// </summary>
/// <returns></returns>
public FileResult ExportExcel()
{
//創建Excel文件的對象
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//添加一個sheet
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
//獲取list數據
WinDataEntities db = new WinDataEntities();//EF上下文對象
List<UserInfo> list = db.UserInfo.Where<UserInfo>(u => true).ToList();
//給sheet1添加第一行的頭部標題
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
row1.CreateCell(0).SetCellValue("姓名");
row1.CreateCell(1).SetCellValue("登錄名");
//將數據逐步寫入sheet1各個行
for (int i = 0; i < list.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
rowtemp.CreateCell(0).SetCellValue(list[i].TrueName);
rowtemp.CreateCell(1).SetCellValue(list[i].UserName);
}
// 寫入到客戶端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", "用戶.xls");
}
/// <summary>
/// 批量導入Excel
/// </summary>
/// <returns></returns>
public ActionResult ImportExcel()
{
try
{
HttpPostedFileBase file = Request.Files["file"];//接收客戶端傳遞過來的數據.
if(file==null)
{
return Content("請選擇上傳的Excel文件");
}
else
{
//對文件的格式判斷,此處省略
WinDataEntities db = new WinDataEntities();//EF上下文對象
Stream inputStream = file.InputStream;
HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputStream);
NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
// IRow headerRow = sheet.GetRow(0);//第一行為標題行
// int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
NewUser model = new NewUser();
if (row != null)
{
if (row.GetCell(0) != null)
{
model.TrueName = GetCellValue(row.GetCell(0));
}
if (row.GetCell(1) != null)
{
model.LoginName = GetCellValue(row.GetCell(1));
}
}
db.NewUser.Add(model);
}
db.SaveChanges();
return Content("導入成功");
}
}
catch (Exception)
{
return Content("導入失敗");
}
}
/// <summary>
/// 根據Excel列類型獲取列的值
/// </summary>
/// <param name="cell">Excel列</param>
/// <returns></returns>
private static string GetCellValue(ICell cell)
{
if (cell == null)
return string.Empty;
switch (cell.CellType)
{
case CellType.Blank:
return string.Empty;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return cell.ErrorCellValue.ToString();
case CellType.Numeric:
case CellType.Unknown:
default:
return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
case CellType.String:
return cell.StringCellValue;
case CellType.Formula:
try
{
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
catch
{
return cell.NumericCellValue.ToString();
}
}
}
}
