示例#1
0
        public void ExportExcel()
        {
            HoaDonModel hoaDon = new HoaDonModel();

            try
            {
                ExcelPackage   pck = new ExcelPackage();
                ExcelWorksheet ws  = pck.Workbook.Worksheets.Add("Report");

                ws.Cells["A1"].Value = "Đơn vị";
                ws.Cells["B1"].Value = "Kí túc zá ĐHQN";

                ws.Cells["A2"].Value = "Ngày";
                ws.Cells["B2"].Value = string.Format("{0: dd MM yyyy} at {0:H: mm tt}", DateTimeOffset.Now);

                ws.Cells["C3"].Value = "HÓA ĐƠN";

                ws.Cells["A5"].Value = "Mã hóa đơn";
                ws.Cells["B5"].Value = "Mã nhân viên";
                ws.Cells["C5"].Value = "Mã phòng";
                ws.Cells["D5"].Value = "Ngày ghi";
                ws.Cells["E5"].Value = "Tổng tiền";

                int rowStar = 6;
                foreach (var item in hoaDon.listAll())
                {
                    ws.Cells[string.Format("A{0}", rowStar)].Value = item.MaHD;
                    ws.Cells[string.Format("B{0}", rowStar)].Value = item.MaNV;
                    ws.Cells[string.Format("C{0}", rowStar)].Value = item.MaPhong;
                    ws.Cells[string.Format("D{0}", rowStar)].Value = item.NgayGhi.ToString("MM/dd/yyyy");
                    //tính tổng tiền
                    ws.Cells[string.Format("E{0}", rowStar)].Value = hoaDon.tongTien();
                    rowStar++;
                }
                ws.Cells["A1 : AZ"].AutoFitColumns();
                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment: filename=" + "ExcelExport.xlsx");
                Response.BinaryWrite(pck.GetAsByteArray());
                Response.End();
            }
            catch (Exception ex)
            {
                ViewBag.Result = ex.Message;
            }
        }