Mvc导入导出Excel
@{
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();
row1.CreateCell().SetCellValue("姓名");
row1.CreateCell().SetCellValue("登录名");
//将数据逐步写入sheet1各个行
for (int i = ; i < list.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + );
rowtemp.CreateCell().SetCellValue(list[i].TrueName);
rowtemp.CreateCell().SetCellValue(list[i].UserName);
}
// 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Seek(, 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();
// IRow headerRow = sheet.GetRow(0);//第一行为标题行
// int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
for (int i = (sheet.FirstRowNum + ); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
NewUser model = new NewUser();
if (row != null)
{
if (row.GetCell() != null)
{
model.TrueName = GetCellValue(row.GetCell());
}
if (row.GetCell() != null)
{
model.LoginName = GetCellValue(row.GetCell());
}
}
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();
}
}
}
}
Mvc导入导出Excel的更多相关文章
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
- mvc 导入,导出excel
最近主要做导入excel 在网上查询了代码 public FileResult DownLoadExcelJiZuChaXunGenRenXiaoFeiJiLu() { DataTable dt = ...
- .NET导入导出Excel
若是开发后台系统,ASP.NET MVC中总是涉及了很多导入导出Excel的问题,有的时候处理起来比较烦 如果能使用以下代码解决,就完美了 public class ReportModel { [Ex ...
- NPOI导入导出Excel
.net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交 代码: 第一步. 在页面里面加入2个隐藏的iframe, 如下 ...
- C#中缓存的使用 ajax请求基于restFul的WebApi(post、get、delete、put) 让 .NET 更方便的导入导出 Excel .net core api +swagger(一个简单的入门demo 使用codefirst+mysql) C# 位运算详解 c# 交错数组 c# 数组协变 C# 添加Excel表单控件(Form Controls) C#串口通信程序
C#中缓存的使用 缓存的概念及优缺点在这里就不多做介绍,主要介绍一下使用的方法. 1.在ASP.NET中页面缓存的使用方法简单,只需要在aspx页的顶部加上一句声明即可: <%@ Outp ...
- asp.net core web的导入导出excel功能
这里主要记录下asp.net core web页面上进行导入导出excel的操作. 主要是导入,因为现在使用的很多前端框架(例如kendo ui)本身就有导出的功能. 这里使用到EPPlus.Core ...
- ASP.NET Core导入导出Excel文件
ASP.NET Core导入导出Excel文件 希望在ASP.NET Core中导入导出Excel文件,在网上搜了一遍,基本都是使用EPPlus插件,EPPlus挺好用,但商用需要授权,各位码友若有好 ...
- ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...
- thinkphp导入导出excel表单数据
在PHP项目经常要导入导出Excel表单. 先去下载PHPExcel类库文件,放到相应位置. 我在thinkphp框架中的位置为ThinkPHP/Library/Org/Util/ 导入 在页面上传e ...
随机推荐
- 让ecshop用户名、手机号、email登陆方法
让ecshop用户名.手机号.email登陆方法, 仅适用于没有做过任何平台整合的ECSHOP网站 修改文件: 1.includes/modules/integrates/ecshop.php ...
- What is the difference between a Clustered and Non Clustered Index?
A clustered index determines the order in which the rows of a table are stored on disk. If a table h ...
- JS之访问器
1.在对象中定义get,set访问器属性 <script> var test = { _name:"pmx", _age:18, _born:1990, get nam ...
- angularJs禁用或启用输入框指令ng-disabled="true"
ng-disabled 指令设置表单输入字段的 disabled 属性(input, select, 或 textarea). 如果 ng-disabled 中的表达式返回 true 则表单字段将被禁 ...
- eNSP的使用
1- 进入华为路由器界面配置ipThe device is running!####################################Nov 1 2016 23:39:24-08:00 ...
- HTTP协议上传boundary确定&下载content-disposition理解
HTTP协议上传文件-协议 上传文件需要将form标签 的 ENCTYPE 属性设置为 multipart/form-data属性, 与 application/x-www-form-urlencod ...
- 关于thenao.scan() fn函数参数的说明
theano.scan()原型: theano.scan( fn, sequences=None, outputs_info=None, non_sequences=None, n_steps=Non ...
- .net mvc onexception capture; redirectresult;
need to set filtercontext.result=new redirectresult('linkcustompage'); done. so... ASP.NET MVC异常处理模块 ...
- zjuoj 3608 Signal Detection
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3608 Signal Detection Time Limit: 2 Sec ...
- sdutoj 2608 Alice and Bob
http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2608 Alice and Bob Time L ...