标签:
MVC中将查询数据列表导出指定格式的excel格式
首先获取导出数据
IPageOfItems<OrderCash> OrderCashList = Entity.Selects<OrderCash>(p);
加载之前定义好的模板,实例化ExcelPackage类
string tempname = "bank.xlsx"; //定义好的导出模板 string file = Server.MapPath("/template") + "\\" + tempname; //模板存放路径 ExcelPackage package = new ExcelPackage(new FileInfo(file), true); //实例化
下面开始加载数据了
if (OrderCashList.Count() > 0) { //加载模板第一张表 var sheet = package.Workbook.Worksheets[1];
var cells = sheet.Cells; int Rows = OrderCashList.Count(); int Befor = 2;//从第几行开始,行号从1开始 sheet.InsertRow(Befor + 1, Rows - 1, Befor); int i = Befor; foreach (var item in OrderCashList) { //业务参考号 cells["A" + i].Value = item.OId; cells["B" + i].Value = ""; cells["C" + i].Value = ""; cells["D" + i].Value = ""; cells["E" + i].Value = ""; cells["F" + i].Value = item.CardNum; cells["G" + i].Value = item.Owner; cells["H" + i].Value = item.Bin; cells["I" + i].Value = item.Amoney - (decimal)item.UserRate; cells["J" + i].Value = "人民币"; cells["K" + i].Value = ""; cells["L" + i].Value = ""; cells["M" + i].Value = ""; cells["N" + i].Value = item.Mobile; cells["O" + i].Value = ""; i++; }
}
数据加载完成后,直接输出就可以了
Response.BinaryWrite(package.GetAsByteArray());//输出 Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(10, 99) + ".xlsx");
是不是很简单
标签:
原文地址:http://www.cnblogs.com/gaojin/p/5740414.html