MVC中用NPOI导出Excel相关问题

时间:2023-03-09 15:41:36
MVC中用NPOI导出Excel相关问题

情形1:可以直接带参数

前端页面:

@.ActionLink("导出Excel", "DownLoadExcel", new { 参数名= '参数值' }, new { style = "margin-right:10px;", @class = "btn btn-green search" })

style 和 class 都可以添加样式

controller导出方法(可以直接将Excel导出 浏览器建议用谷歌)

方法如下:

public System.Web.Mvc.FileResult DownLoadExcel(string Id)

{

int ClassId = Convert.ToInt32(Request["ClassId"]);
string[] titleList = new string[] { "编号", "学员姓名", "单位", "联系方式", "身份证号码", "缴费情况", "缴费方式", "所在班级", "备注信息" };
IList<MODEL.Train.V_TrainProgramDetail> list = GetData()//获取数据方法 //创建Excel文件的对象
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//添加一个sheet
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
//给sheet1添加第一行的头部标题
IRow headerrow = sheet1.CreateRow(); HSSFCellStyle headStyle = (HSSFCellStyle)book.CreateCellStyle();
HSSFFont font = (HSSFFont)book.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font);
for (int i = ; i < titleList.Length; i++)
{
ICell cell = headerrow.CreateCell(i);
cell.CellStyle = headStyle;
cell.SetCellValue(titleList[i]);
} //将数据逐步写入sheet1各个行
for (int i = ; i < list.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + );
rowtemp.CreateCell().SetCellValue(list[i].Id.ToString());
rowtemp.CreateCell().SetCellValue(list[i].CompanyName);
rowtemp.CreateCell().SetCellValue(list[i].CompanyName);
rowtemp.CreateCell().SetCellValue(list[i].Phone);
rowtemp.CreateCell().SetCellValue(list[i].IDCard);
rowtemp.CreateCell().SetCellValue(list[i].IsPay.ToString());
rowtemp.CreateCell().SetCellValue(list[i].SignUpType.ToString());
rowtemp.CreateCell().SetCellValue(list[i].ClassName);
rowtemp.CreateCell().SetCellValue("");
}
// 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Seek(, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", "学员报名详情.xls");

}

情形2:不能直接带参数,需要用到ajax

前端页面:

         <div class="modal-content">
<div class="modal-header" style="height:120px;">
<button type="button" class="close" data-dissmiss="modal" aria-hidden="true" onclick="CancleImportExcel()">&times;</button>
<h4 id="title">请选择时间范围</h4>
<div class="modal-dialog container">
<div class="row">
<div class="col-xs-6">
<input type="hidden" name="id" id="id" />
<label>订单开始时间:</label>
<span>
<input type="text" id="OrderStartTime" name="OrderStartTime" onclick="WdatePicker({ dateFmt:'yyyy-MM-dd HH:mm:ss' })" class="Wdate" />
</span>
</div>
<div class="col-xs-6">
<label>结束时间:</label>
<span>
<input type="text" id="OrderEndTime" name="OrderEndTime" onclick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss' })" class="Wdate" />
</span>
</div>
</div>
</div>
</div>
<div class="modal-footer"><button type="button" class="btn btn-default" data-dissmiss="modal" onclick="Export()">确定</button>
</div>
</div> <script>

function Export() {
var param = {
OrderStartTime: $("#OrderStartTime").val(),
OrderEndTime: $("#OrderEndTime").val()
};
$.ajax({
url: '/Order/DownLoadExcel', //Controller名称和方法名
type: "POST",
dataType: "json",
data: param,
success: function (data) {

//重定向返回参数
location.href = "/Order/OutExcel?guid=" + data;

});
}

</script>

Controller方法如下:

public ActionResult DownLoadExcel()
{
#region 查询数据
string OrderStartTime = Convert.ToDateTime(Request["OrderStartTime"]).ToString("yyyy-MM-dd");
string OrderEndTime = Convert.ToDateTime(Request["OrderEndTime"]).AddDays().ToString("yyyy-MM-dd"); string[] titleList = new string[] { "序号", "订单编号", "收货人", "送货单位", "送货地址", "商品编号", "商品名称", "联系电话", "总价", "订单状态", "创建时间", "配送时间", "备注信息" };
IList<Model.Order.OrderInfo> list = OrderInfoBLL.GetOrdersInfoListByTime(OrderStartTime, OrderEndTime);
#endregion #region NPOI数据导出
//创建Excel文件的对象
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//添加一个sheet
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
//给sheet1添加第一行的头部标题
IRow headerrow = sheet1.CreateRow(); HSSFCellStyle headStyle = (HSSFCellStyle)book.CreateCellStyle();
HSSFFont font = (HSSFFont)book.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font);
for (int i = ; i < titleList.Length; i++)
{
ICell cell = headerrow.CreateCell(i);
cell.CellStyle = headStyle;
cell.SetCellValue(titleList[i]);
}
//将数据逐步写入sheet1各个行
for (int i = ; i < list.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + );
rowtemp.CreateCell().SetCellValue(i + );
rowtemp.CreateCell().SetCellValue(list[i].No);
rowtemp.CreateCell().SetCellValue(list[i].Receiver);
rowtemp.CreateCell().SetCellValue(list[i].Company);
rowtemp.CreateCell().SetCellValue(list[i].Address);
rowtemp.CreateCell().SetCellValue(list[i].CargoNo);
rowtemp.CreateCell().SetCellValue(list[i].CargoName);
rowtemp.CreateCell().SetCellValue(list[i].Phone);
rowtemp.CreateCell().SetCellValue(list[i].Prices.ToString());
rowtemp.CreateCell().SetCellValue(list[i].Status == ? "待审核" : list[i].Status == ? "已审核待收货" : list[i].Status == ? "已收货已完成" : "取消审核不通过");
rowtemp.CreateCell().SetCellValue(list[i].CreateDate.ToString("yyyy-MM-dd"));
rowtemp.CreateCell().SetCellValue(list[i].DeliveryTime.ToString("yyyy-MM-dd HH:mm"));
rowtemp.CreateCell().SetCellValue("");
}
var guid = Guid.NewGuid().ToString();
DownLoadHelper.SetCache(guid, book);
return Json(guid, JsonRequestBehavior.AllowGet);
#endregion
}

public void OutExcel(string guid)
{
object obj = DownLoadHelper.GetCache(guid);
NPOI.HSSF.UserModel.HSSFWorkbook book = obj as NPOI.HSSF.UserModel.HSSFWorkbook;
if (book != null)
{
//写入到客户端
MemoryStream ms = new MemoryStream();
book.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
Response.BinaryWrite(ms.ToArray());
book = null;
ms.Close();
ms.Dispose();
}
DownLoadHelper.RemoveAllCache(guid);
}

 

就是在Controller不支持直接导出Excel的时候  分两步骤 1: 要先将导出内容保存在缓存中 2: 利用ajax的重定向再将Excel数据导出

下面是DownLoadHelper类方法:

public class DownLoadHelper
{
#region 获取缓存
public static object GetCache(string cacheKey)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[cacheKey];
}
#endregion #region 设置数据缓存
public static void SetCache(string cacheKey, object objObject)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(cacheKey, objObject);
} public static void SetCache(string cacheKey, object objObject, TimeSpan timeOut)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
} public static void SetCache(string cacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(cacheKey, objObject, null, absoluteExpiration, slidingExpiration);
} #endregion #region 移除数据缓存
public static void RemoveAllCache(string cacheKey)
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
_cache.Remove(cacheKey);
} public static void RemoveAllCache()
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
IDictionaryEnumerator cacheEnum = _cache.GetEnumerator();
while (cacheEnum.MoveNext())
{
_cache.Remove(cacheEnum.Key.ToString());
}
}
#endregion
}

希望能对遇到此类问题的朋友有所帮助!