Exportar a Excel en ASP.Net Core 2.0

 C Programming >> Programación C >  >> Tags >> Excel
Exportar a Excel en ASP.Net Core 2.0

Hay muchas maneras de lograr eso.

Opción 1:guardar en wwwroot

Puede generar el Excel y guardarlo en el wwwroot carpeta. Y luego puede publicarlo como contenido estático en la página.

Por ejemplo, tiene una carpeta llamada 'temp' dentro del wwwroot carpeta para contener todos los Excel recién generados.

<a href="\temp\development\user1\2018\5\9\excel1.xlsx" download>Download</a>

Hay limitaciones en este enfoque. 1 de ellos es el nuevo download atributo. Solo funciona en navegadores modernos.

Opción 2:matriz de bytes

Otra forma es generar el Excel, convertirlo en una matriz de bytes y enviarlo de vuelta al controlador. Para eso utilizo una biblioteca llamada "EPPlus" (v:4.5.1) que soporta .Net Core 2.0.

Los siguientes son solo algunos códigos de muestra que junté para darle una idea. No está listo para la producción.

using OfficeOpenXml;
using OfficeOpenXml.Style;

namespace DL.SO.Web.UI.Controllers
{
    public class ExcelController : Controller
    {
        public IActionResult Download()
        {
            byte[] fileContents;

            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("Sheet1");

                // Put whatever you want here in the sheet
                // For example, for cell on row1 col1
                worksheet.Cells[1, 1].Value = "Long text";

                worksheet.Cells[1, 1].Style.Font.Size = 12;
                worksheet.Cells[1, 1].Style.Font.Bold = true;

                worksheet.Cells[1, 1].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                // So many things you can try but you got the idea.

                // Finally when you're done, export it to byte array.
                fileContents = package.GetAsByteArray();
            }

            if (fileContents == null || fileContents.Length == 0)
            {
                return NotFound();
            }

            return File(
                fileContents: fileContents,
                contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                fileDownloadName: "test.xlsx"
            );
        }
    }
}

De acuerdo con la respuesta de David Liang.

Modificaciones de diapositivas si desea exportar toda la tabla de datos.

            string export="export";
            DataTable dt = new DataTable();
            //Fill datatable
            dt = *something*

            byte[] fileContents;
            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add(export);
                worksheet.Cells["A1"].LoadFromDataTable(dt, true);
                fileContents = package.GetAsByteArray();
            }
            if (fileContents == null || fileContents.Length == 0)
            {
                return NotFound();
            }
            return File(
                fileContents: fileContents,
                contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                fileDownloadName: export + ".xlsx"
            );