您的位置:首页 > 编程语言 > ASP

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下来

源码下载:下载

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: