Export excel from datatable ASP using Epplus

0 thích 0 không thích
1 lượt xem
đã hỏi 9 Tháng 11, 2022 trong Lập trình C# bởi nguyenthao (8,120 điểm)
 public void ExportExcel(DataTable dataTable, string fileName, string sheetName = "Sheet 1", string beginWriteCell= "A1", bool isAutoFitColumns = false, bool isFilter = false, bool isBorder = false) {
       var stream = new MemoryStream();
        using (ExcelPackage pck = new ExcelPackage(stream))
        {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add(sheetName);
            ws.Cells[beginWriteCell].LoadFromDataTable(dataTable, true);
            if (isFilter)
            {
                ws.Cells[ws.Dimension.Address].AutoFilter = true;
            }
            if (isAutoFitColumns)
            {
                ws.Cells[ws.Dimension.Address].AutoFitColumns();
            }
            if (isBorder)
            {
                ws.Cells[ws.Dimension.Address].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                ws.Cells[ws.Dimension.Address].Style.Border.Left.Style = ExcelBorderStyle.Thin;
                ws.Cells[ws.Dimension.Address].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                ws.Cells[ws.Dimension.Address].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

            }

            pck.Save();
        }

        Response.Clear();
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=" + fileName);
        Response.AddHeader("Content-Length", stream.Length.ToString());
        Response.BinaryWrite(stream.ToArray());
        Response.End();

        stream.Close();

       
    }

Looking for an answer?  Share this question:     

Xin vui lòng đăng nhập hoặc đăng ký để trả lời câu hỏi này.

...