ASP.NET MVC4 导出Excel问题
2016-07-15 17:56
691 查看
做项目中遇到导出数据问题,基本网上搜索一大堆,无外乎生成xml格式的html或是调用office组件,但总体用下来觉得不好;通过寻觅发现在MVC架构中有一个很好的nuGet package:EPPlus
实现数据源导出Excel非常棒!
详见:https://gallery.technet.microsoft.com/scriptcenter/export-to-excel-in-aspnet-cf17ea0d
防止哪天外网又被屏蔽,原文copy下来
源码下载:下载
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
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 in the below figure.
As per the above process, we need four operations here. These are as follows,
Data: We use static data to keep this example simple.
List: Static data store in a List<T>.
Data Table : Convert List<T> in to DataTable.
Export: DataTable exports to excel file.
we create export to excel functionality helper class which has the following features.
Convert List<T> to DataTable method
Customize the columns which need to export means dynamically choose columns which will be export from list to Excel.
Serial number in Excel sheet.
Add and Remove functionality for the custom heading in Excel sheet.
Excel sheet heading with colors.
Dynamic name for worksheet.
The following code snippet is used for the class ExcelExportHelper
C#代码:
The article link is http://www.c-sharpcorner.com/article/export-to-excel-in-asp-net-mvc
实现数据源导出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 in the below figure.
As per the above process, we need four operations here. These are as follows,
Data: We use static data to keep this example simple.
List: Static data store in a List<T>.
Data Table : Convert List<T> in to DataTable.
Export: DataTable exports to excel file.
we create export to excel functionality helper class which has the following features.
Convert List<T> to DataTable method
Customize the columns which need to export means dynamically choose columns which will be export from list to Excel.
Serial number in Excel sheet.
Add and Remove functionality for the custom heading in Excel sheet.
Excel sheet heading with colors.
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
相关文章推荐
- 使用jaspersoft创建jasper模板的经验总结
- ASP.NET MVC路由系统的核心对象介绍
- ASP.Net Core-依赖注入IoC
- asp.net获取文件夹下的所有文件
- ExtJS 6 Grid使用示例(ASP.NET MVC4 项目)
- ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0
- 如何破解aspose.words
- 七天学会ASP.NET MVC(七)——创建单页应用
- ASP.NET Core开发-使用Nancy框架
- 有哪些对树莓派 (Raspberry Pi) 的有趣改造、扩展应用?
- 解决asp.net FileUpload控件无法获取完整路径的问题 - 无序修改浏览器参数
- Metasploit详解 详细图文教程
- Asp.Net Core WebApi学习笔记(四)-- Middleware
- yoeman构建Asp.net core项目并且实现分层
- 七天学会ASP.NET MVC (一)——深入理解ASP.NET MVC
- 【Asp.Net Core】二、添加控制器和视图
- 在Mac上开发使用yoeman构建Asp.net core项目并且实现分层引用
- ASP.NET MVC进阶之路:依赖注入(Di)和Ninject
- asp.net MVC EFCodeFirst 生成数据库注意事项
- asp.net mvc code first实体关系一对一、一对多、多对多的设置方法