mvc导出excel
//导出表格
function ExportUser() {
var $form = $('<form target="down-file-iframe" method="post" />');
$form.attr('action', "/Employee/Export");
var username = $.trim($("#searchkey").val());
var deptid = $("#deptid").val();
$form.append('<input type="hidden" name="mastername" value="' + username+ '" />');
$form.append('<input type="hidden" name="deptid" value="' + deptid + '" />');
$(document.body).append($form);
$form.submit();
$form.remove();
}
#region 导出
[HttpPost]
public FileResult Export([System.Web.Http.FromBody]User masterInfo)
{
var list=new User();//获取数据
HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();//创建工作簿
string tmpTitle = "用户" + DateTime.Now.ToString("yyyy-MM-dd");
ISheet sheet = book.CreateSheet(tmpTitle);//创建一个名为 taskTitle 的表
IRow headerrow = sheet.CreateRow(0);//创建一行,此行为第一行
ICellStyle style = book.CreateCellStyle();//创建表格样式
style.Alignment = HorizontalAlignment.Center;//水平对齐方式
style.VerticalAlignment = VerticalAlignment.Center;//垂直对齐方式
//给 sheet 添加第一行的头部标题
headerrow.CreateCell(0).SetCellValue("序号");
headerrow.CreateCell(1).SetCellValue("用户名");
headerrow.CreateCell(2).SetCellValue("真实姓名");
headerrow.CreateCell(3).SetCellValue("角色");
headerrow.CreateCell(4).SetCellValue("所属部门");
for (int i = 0; i < list.Count; i++)
{
vw_user userinfo = list[i];
IRow row = sheet.CreateRow(i + 1); //新创建一行
ICell cell = row.CreateCell(i); //在新创建的一行中创建单元格
cell.CellStyle = style; //设置单元格格式
row.CreateCell(0).SetCellValue(i + 1); //给单元格赋值
row.CreateCell(1).SetCellValue(userinfo.mastername);
row.CreateCell(2).SetCellValue(userinfo.truename);
row.CreateCell(3).SetCellValue(userinfo.groupname);
row.CreateCell(4).SetCellValue(userinfo.deptname);
}
MemoryStream ms = new MemoryStream();
book.Write(ms);
string UserAgent = System.Web.HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower();
if (UserAgent.IndexOf("firefox") == -1)
{
tmpTitle = HttpUtility.UrlEncode(tmpTitle, System.Text.Encoding.UTF8).Replace("+", "%20").Replace("%27", "'");
}
else
{
tmpTitle = "=?UTF-8?B?" + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(tmpTitle)) + "?=";
}
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "application/excel", tmpTitle + ".xls");
}
#endregion