ASP.NET MVC4 导出Excel问题

本文介绍如何在ASP.NET MVC项目中使用EPPlus NuGet包将数据导出到Excel文件。文章提供了完整的步骤,包括安装EPPlus、创建数据集、转换为DataTable以及最终的Excel导出过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做项目中遇到导出数据问题,基本网上搜索一大堆,无外乎生成xml格式的html或是调用office组件,但总体用下来觉得不好;通过寻觅发现在MVC架构中有一个很好的nuGet package:EPPlus

实现数据源导出Excel非常棒!

详见:https://gallery.technet.microsoft.com/scriptcenter/export-to-excel-in-aspnet-cf17ea0d

防止哪天外网又被屏蔽,原文copy下来

源码下载:下载

Export To Excel In ASP.NET MVC

This introduces how to export data in an Excel file in ASP.NET MVC.We install EPPlus nuGet package in the application to implement export to excel funtionlity.When we use ORM in our application, we keep most of the data in the collection which easily converts it in a list. The li

This introduces how to export data in an Excel file in ASP.NET MVC.We install EPPlus nuGet package in the application to implement export to excel funtionlity.

When we use ORM in our application, we keep most of the data in the collection which easily converts it in a list. The list can’t be exported to the Excel directly. That’s why we need to convert this list in data table first. After that, this data table can be exported in the Excel file as shown i
n the below figure.

As per the above process, we need four operations here. These are as follows,

  1. Data: We use static data to keep this example simple.
  2. List: Static data store in a List<T>.
  3. Data Table : Convert List<T> in to DataTable.
  4. Export: DataTable exports to excel file.

we create export to excel functionality helper class which has the following features. 

  1. Convert List<T> to DataTable method
  2. Customize the columns which need to export means dynamically choose columns which will be export from list to Excel.
  3. Serial number in Excel sheet.
  4. Add and Remove functionality for the custom heading in Excel sheet.
  5. Excel sheet heading with colors.
  6. Dynamic name for worksheet.

The following code snippet is used for the class ExcelExportHelper

C#代码:

using OfficeOpenXml; 
using OfficeOpenXml.Style; 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Linq; 
 
namespace ExportExcel.Code 
{ 
    public class ExcelExportHelper 
    { 
        public static string ExcelContentType 
        { 
            get 
            { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } 
        } 
 
        public static DataTable ListToDataTable<T>(List<T> data) 
        { 
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); 
            DataTable dataTable = new DataTable(); 
 
            for (int i = 0; i < properties.Count; i++) 
            { 
                PropertyDescriptor property = properties[i]; 
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType); 
            } 
 
            object[] values = new object[properties.Count]; 
            foreach (T item in data) 
            { 
                for (int i = 0; i < values.Length; i++) 
                { 
                    values[i] = properties[i].GetValue(item); 
                } 
 
                dataTable.Rows.Add(values); 
            } 
            return dataTable; 
        } 
 
        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake) 
        { 
 
            byte[] result = null; 
            using (ExcelPackage package = new ExcelPackage()) 
            { 
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data",heading)); 
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3; 
 
                if (showSrNo) 
                { 
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int)); 
                    dataColumn.SetOrdinal(0); 
                    int index = 1; 
                    foreach (DataRow item in dataTable.Rows) 
                    { 
                        item[0] = index; 
                        index++; 
                    } 
                } 
 
 
                // add the content into the Excel file 
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true); 
 
                // autofit width of cells with small content 
                int columnIndex = 1; 
                foreach (DataColumn column in dataTable.Columns) 
                { 
                    ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex]; 
                    int maxLength = columnCells.Max(cell => cell.Value.ToString().Count()); 
                    if (maxLength < 150) 
                    { 
                        workSheet.Column(columnIndex).AutoFit(); 
                    } 
 
 
                    columnIndex++; 
                } 
 
                // format header - bold, yellow on black 
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count]) 
                { 
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White); 
                    r.Style.Font.Bold = true; 
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; 
                    r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad")); 
                } 
 
                // format cells - add borders 
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count]) 
                { 
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin; 
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; 
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin; 
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin; 
 
                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black); 
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black); 
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black); 
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black); 
                } 
 
                // removed ignored columns 
                for (int i = dataTable.Columns.Count - 1; i >= 0; i--) 
                { 
                    if (i == 0 && showSrNo) 
                    { 
                        continue; 
                    } 
                    if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName)) 
                    { 
                        workSheet.DeleteColumn(i + 1); 
                    } 
                } 
 
                if (!String.IsNullOrEmpty(heading)) 
                { 
                    workSheet.Cells["A1"].Value = heading; 
                    workSheet.Cells["A1"].Style.Font.Size = 20; 
 
                    workSheet.InsertColumn(1, 1); 
                    workSheet.InsertRow(1, 1); 
                    workSheet.Column(1).Width = 5; 
                } 
 
                result = package.GetAsByteArray(); 
            } 
 
            return result; 
        } 
 
        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake) 
        { 
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake); 
        } 
 
    } 
}


The article link is http://www.c-sharpcorner.com/article/export-to-excel-in-asp-net-mvc


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石头商人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值