標籤:
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");
是不是很簡單
MVC使用ExcelPackage匯出Excel檔案