首页 > 技术文章 > 1.ASP.NET MVC使用EPPlus,导出数据到Excel中

caofangsheng 2016-12-09 15:52 原文

好久没写博客了,今天特地来更新一下,今天我们要学习的是如何导出数据到Excel文件中,这里我使用的是免费开源的Epplus组件。

源代码下载:https://github.com/caofangsheng93/ExcelExportInMvc

介绍

这篇文章,介绍的是怎样导出数据到Excel文件中,大多数的后端程序都有报表功能:把显示在Grid中的数据导出到Excel文件中,这篇文章中使用的是EPPlus组件。

EPPlus是一个基于OOXML【Open Extended Markup Language 】格式的,操作Excel表格的类库。OOXML是由微软开发的。默认支持微软的Office。

 开源网站:http://epplus.codeplex.com/

正文

上面是我们的项目。

首先我们需要引入:EPPlus。

我这里已经引入了。

当我们在程序中使用ORM的时候,我们通常将数据保存在集合中。集合中的数据不能直接导出到Excel文件中。这也就是我们为啥,需要先将List转DataTable的原因。

 Process Export to Excel

                                  图1 :导出Excel的步骤

 

 

为了完成这篇文章:我们需要四个步骤:

1.数据:这里我使用静态数据,来确保这篇文章尽可能通俗易懂。

2.集合:静态数据保存在集合中

3.DataTable:转化泛型集合的数据,保存到DataTable中

4.导出文件:DataTable导出为Excel

 

首先,我们创建一个类:

 public class Student
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public string Sex { get; set; }

        public int Age { get; set; }

        public string Email { get; set; }
    }
Student

 

然后创建一个静态数据类:

public class StaticDataOfStudent
    {
        public static List<Student> ListStudent
        {
            get 
            {
                return new List<Student>() 
                {
                new Student(){ID=1,Name="曹操",Sex="",Email="caocao@163.com",Age=24},
                new Student(){ID=2,Name="李易峰",Sex="",Email="lilingjie@sina.com.cn",Age=24},
                new Student(){ID=3,Name="张三丰",Sex="",Email="zhangsanfeng@qq.com",Age=224},
                new Student(){ID=4,Name="孙权",Sex="",Email="sunquan@163.com",Age=1224},
                };
            }
        }
    }
StaticDataOfStudent

 

然后就是我们的导出Excel帮助类了:

  /// <summary>
    /// Excel导出帮助类
    /// </summary>
    public class ExcelExportHelper
    {
        public static string ExcelContentType
        {
            get 
            {
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }
        }

        /// <summary>
        /// List转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        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;  
        }


        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="dataTable">数据源</param>
        /// <param name="heading">工作簿Worksheet</param>
        /// <param name="showSrNo">//是否显示行编号</param>
        /// <param name="columnsToTake">要导出的列</param>
        /// <returns></returns>
        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 Content Into the Excel File
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
                // autofit width of cells with small content  
                int columnIndex = 1;
                foreach (DataColumn item 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;
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="heading"></param>
        /// <param name="isShowSlNo"></param>
        /// <param name="ColumnsToTake"></param>
        /// <returns></returns>
        public static byte[] ExportExcel<T>(List<T> data, string heading = "", bool isShowSlNo = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), heading, isShowSlNo, ColumnsToTake);  
        }

    }

 

到此为止,后端服务器的代码,基本搞完,现在开始设计我们的前端代码:

我们创建一个ViewModel,用来显示数据:

public class StudentViewModel
    {
        public List<Student> ListStudent
        {
            get 
            {
                return StaticDataOfStudent.ListStudent;
            }
        }
    }

然后创建一个控制器:

 public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            StudentViewModel model = new StudentViewModel();
            return View(model);
        }

        public FileContentResult ExportToExcel()
        {
            List<Student> lstStudent = StaticDataOfStudent.ListStudent;
            string[] columns = { "ID", "Name","Age"};
            byte[] filecontent = ExcelExportHelper.ExportExcel(lstStudent,"", false, columns);
            return File(filecontent, ExcelExportHelper.ExcelContentType, "MyStudent.xlsx");  
        }
    }

我们的视图代码:

@model ExportToExcel.Models.StudentViewModel
@{
    ViewBag.Title = "Excel文件导出";
}
<div class="panel">
    <div class="panel-heading">
        <a href="@Url.Action("ExportToExcel")" class="btn btn-primary">Export</a>
    </div>
    <div class="panel-body">
        <table class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Sex</th>
                    <th>Age</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.ListStudent)
                {
                    <tr>
                        <td>@item.ID</td>
                        <td>@item.Name</td>
                        <td>@item.Sex</td>
                        <td>@item.Age</td>
                        <td>@item.Email</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>
  

 

效果图:

点击Export之后,就导出了Excel文件到浏览器中:打开之后。

 

 

 总结:这个导出帮助类,可以定制导出那些列。

            string[] columns = { "ID", "Name","Age"};
            byte[] filecontent = ExcelExportHelper.ExportExcel(lstStudent,"", false, columns);
            return File(filecontent, ExcelExportHelper.ExcelContentType, "MyStudent.xlsx");  
这里我只是导出这三列。

类似资料参考:http://www.cnblogs.com/liudeyun/p/3535740.html

 

推荐阅读