Home > Backend Development > C++ > How to Efficiently Export Data to Excel Using EPPlus?

How to Efficiently Export Data to Excel Using EPPlus?

Barbara Streisand
Release: 2025-01-05 15:28:40
Original
275 people have browsed it

How to Efficiently Export Data to Excel Using EPPlus?

How to Export Data to Excel

The provided guide demonstrates a workaround for generating HTML files with tables, but this approach can be unreliable when Excel interprets and imports these files. A more effective method is to create a dedicated Excel file using a library such as EPPlus.

Using EPPlus

EPPlus offers the LoadFromDataTable and LoadFromCollection methods to populate an Excel range with data from a data table or a generic collection, respectively. The column or property names serve as headers during loading.

Example Code:

public ActionResult ExportData()
{
    DataTable dataTable = GetData(); // Method to retrieve data

    using (ExcelPackage package = new ExcelPackage())
    {
        var ws = package.Workbook.Worksheets.Add("My Sheet");
        ws.Cells["A1"].LoadFromDataTable(dataTable, true); // Load with true to include headers

        var stream = new MemoryStream();
        package.SaveAs(stream);

        string fileName = "myfilename.xlsx";
        string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        stream.Position = 0;
        return File(stream, contentType, fileName);
    }
}
Copy after login

Formatting and Styling:

Once data is loaded, you can further customize and style the Excel range:

var range = ws.Cells["A1"].LoadFromDataTable(table);
range.Style.Numberformat.Format = "#,##0.00"; // Set number format
range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right; // Set horizontal alignment
Copy after login

Customizing Output:

To alleviate potential issues when creating large files, or to avoid duplicate writes, you can create a custom FileResult handler for EPPlus packages:

public class EpplusResult : FileResult
{
    public EpplusResult(ExcelPackage package)
        : base("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    {
        Package = package;
    }

    public ExcelPackage Package { get; private set; }

    protected override void WriteFile(HttpResponseBase response)
    {
        using (Package)
        {
            Package.SaveAs(response.OutputStream);
        }
    }
}
Copy after login

This custom result can then be used in the controller action:

public FileResult ExportData()
{
    ExcelPackage package = new ExcelPackage();
    var ws = package.Workbook.Worksheets.Add("My Sheet");
    ... // Load and format data

    return new EpplusResult(package) { FileDownloadName = "SomeFile.xlsx" };
}
Copy after login

This approach ensures direct writing to the output stream, optimizing performance for large files.

The above is the detailed content of How to Efficiently Export Data to Excel Using EPPlus?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template