简介:Epplus是一个使用Open Office XML(Xlsx)文件格式,能读写Excel 2007/2010文件的开源组件

功效:支持对excel文档的汇入汇出,图表(excel自带的图表基本都可以实现)的列印
安装:NuGet
 
导出思路:

准备:

1.创建对象

  1. namespace Models
  2. {
  3.     public class Student
  4.     {
  5.         public int ID { get; set; }
  6.         public string Name { get; set; }
  7.         public string Sex { get; set; }
  8.         public int Age { get; set; }
  9.         public string Email { get; set; }
  10.     }
  11. }

1.创建Excel帮助类

  1. using OfficeOpenXml;
  2. using OfficeOpenXml.Style;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Linq;
  8.  
  9. namespace Common
  10. {
  11.     /// <summary>
  12.     /// Excel导出帮助类
  13.     /// </summary>
  14.     public class ExcelExportHelper
  15.     {
  16.         public static string ExcelContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  17.         /// <summary>
  18.         /// List转DataTable
  19.         /// </summary>
  20.         /// <typeparam name="T"></typeparam>
  21.         /// <param name="data"></param>
  22.         /// <returns></returns>
  23.         public static DataTable ListToDataTable<T>(List<T> data)
  24.         {
  25.             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
  26.             DataTable dataTable = new DataTable();
  27.             for (int i = 0; i < properties.Count; i++)
  28.             {
  29.                 PropertyDescriptor property = properties[i];
  30.                 dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
  31.             }
  32.             object[] values = new object[properties.Count];
  33.             foreach (T item in data)
  34.             {
  35.                 for (int i = 0; i < values.Length; i++)
  36.                 {
  37.                     values[i] = properties[i].GetValue(item);
  38.                 }
  39.                 dataTable.Rows.Add(values);
  40.             }
  41.             return dataTable;
  42.         }
  43.  
  44.         /// <summary>
  45.         /// 导出Excel
  46.         /// </summary>
  47.         /// <param name="dataTable">数据源</param>
  48.         /// <param name="heading">工作簿Worksheet</param>
  49.         /// <param name="showSrNo">//是否显示行编号</param>
  50.         /// <param name="columnsToTake">要导出的列</param>
  51.         /// <returns></returns>
  52.         public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
  53.         {
  54.             byte[] result;
  55.             using (ExcelPackage package = new ExcelPackage())
  56.             {
  57.                 ExcelWorksheet workSheet = package.Workbook.Worksheets.Add($"{heading}Data");
  58.                 int startRowFrom = string.IsNullOrEmpty(heading) ? 1 : 3;  //开始的行
  59.                 //是否显示行编号
  60.                 if (showSrNo)
  61.                 {
  62.                     DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
  63.                     dataColumn.SetOrdinal(0);
  64.                     int index = 1;
  65.                     foreach (DataRow item in dataTable.Rows)
  66.                     {
  67.                         item[0] = index;
  68.                         index++;
  69.                     }
  70.                 }
  71.                 //Add Content Into the Excel File
  72.                 workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
  73.                 // autofit width of cells with small content 
  74.                 int columnIndex = 1;
  75.                 foreach (DataColumn item in dataTable.Columns)
  76.                 {
  77.                     ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
  78.                     int maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
  79.                     if (maxLength < 150)
  80.                     {
  81.                         workSheet.Column(columnIndex).AutoFit();
  82.                     }
  83.                     columnIndex++;
  84.                 }
  85.                 // format header - bold, yellow on black 
  86.                 using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
  87.                 {
  88.                     r.Style.Font.Color.SetColor(System.Drawing.Color.White);
  89.                     r.Style.Font.Bold = true;
  90.                     r.Style.Fill.PatternType = ExcelFillStyle.Solid;
  91.                     r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));
  92.                 }
  93.                 // format cells - add borders 
  94.                 using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
  95.                 {
  96.                     r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
  97.                     r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
  98.                     r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
  99.                     r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
  100.                     r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
  101.                     r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
  102.                     r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
  103.                     r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
  104.                 }
  105.                 // removed ignored columns 
  106.                 for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
  107.                 {
  108.                     if (i == 0 && showSrNo)
  109.                     {
  110.                         continue;
  111.                     }
  112.                     if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
  113.                     {
  114.                         workSheet.DeleteColumn(i + 1);
  115.                     }
  116.                 }
  117.                 if (!string.IsNullOrEmpty(heading))
  118.                 {
  119.                     workSheet.Cells["A1"].Value = heading;
  120.                     workSheet.Cells["A1"].Style.Font.Size = 20;
  121.                     workSheet.InsertColumn(1, 1);
  122.                     workSheet.InsertRow(1, 1);
  123.                     workSheet.Column(1).Width = 5;
  124.                 }
  125.                 result = package.GetAsByteArray();
  126.             }
  127.             return result;
  128.         }
  129.         /// <summary>
  130.         /// 导出Excel
  131.         /// </summary>
  132.         /// <typeparam name="T"></typeparam>
  133.         /// <param name="data"></param>
  134.         /// <param name="heading"></param>
  135.         /// <param name="isShowSlNo"></param>
  136.         /// <param name="columnsToTake"></param>
  137.         /// <returns></returns>
  138.         public static byte[] ExportExcel<T>(List<T> data, string heading = "", bool isShowSlNo = false, params string[] columnsToTake)
  139.         {
  140.             return ExportExcel(ListToDataTable(data), heading, isShowSlNo, columnsToTake);
  141.         }
  142.     }
  143. }

3.获取数据并显示

  1. //数据类
using Models;
using System.Collections.Generic;
  1.  
namespace BLL
{
    //数据类
    public class StaticDataOfStudent
    {
        public static List<Student> ListStudent => 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},
        };
    }
}
  1.  
  1. //用于显示的数据类
using BLL;
using Models;
using System.Collections.Generic;
  1.  
namespace EPPlusMvcDemo2.Models
{
    public class StudentViewModel
    {
        public List<Student> ListStudent => StaticDataOfStudent.ListStudent;
    }
}
  1.  

实现部分:

1.控制器

using BLL;
using Common;
using EPPlusMvcDemo2.Models;
using Models;
using System.Collections.Generic;
using System.Web.Mvc;
namespace EPPlusMvcDemo2.Controllers
{
    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");
        }
    }
}

2.视图

  1. @model EPPlusMvcDemo2.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>

原文:https://www.cnblogs.com/caofangsheng/p/6149843.html

C# 使用Epplus导出数据到Excel的更多相关文章

  1. 1.ASP.NET MVC使用EPPlus,导出数据到Excel中

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

  2. 导出数据到Excel --使用ExcelReport有感

    先看图,这是几个月前用NPOI写的导出数据到Excel,用了上百行代码,而且难控制,导出来也比较难看 excel打开的效果 下面是我用ExcelReport类库导出到Excel的操作 1.首先引用Ex ...

  3. 使用Open xml 操作Excel系列之二--从data table导出数据到Excel

    由于Excel中提供了透视表PivotTable,许多项目都使用它来作为数据分析报表. 在有些情况下,我们需要在Excel中设计好模板,包括数据源表,透视表等, 当数据导入到数据源表时,自动更新透视表 ...

  4. Dynamics CRM导出数据到Excel

    原创地址:http://www.cnblogs.com/jfzhu/p/4276212.html 转载请注明出处 Pivot Table是微软BI的一个重要工具,所以这里讲一下Dynamics CRM ...

  5. MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult

    导出EXCEL方法总结 MVC导出数据到EXCEL的方法有很多种,常见的是: 1.采用EXCEL COM组件来动态生成XLS文件并保存到服务器上,然后转到该文件存放路径即可: 优点:可设置丰富的EXC ...

  6. php导出数据到excel,防止身份证等数字字符格式变成科学计数的方法

    而关于php的也有,但是大多都是用phpExcel导出的方法或者spreadsheet等类或者控件之类的导出方法,而我所在维护的系统却用很简单的方法,如下,网上很少有讲如何设置要导出数据的EXcel格 ...

  7. NPOI导出数据到Excel

    NPOI导出数据到Excel   前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微 ...

  8. ASP.NET导出数据到Excel 实例介绍

    ASP.NET导出数据到Excel  该方法只是把asp.net页面保存成html页面只是把后缀改为xlc不过excel可以读取,接下连我看看还有别的方式能导出数据,并利用模版生成. 下面是代码 新建 ...

  9. C#导出数据到Excel通用的方法类

    导出数据到Excel通用的方法类,请应对需求自行修改. 资源下载列表 using System.Data; using System.IO; namespace IM.Common.Tools { p ...

随机推荐

  1. eclipse 代码提示快捷键 alt+/

    eclipse (ALT+/)1.选择Eclipse菜单栏中的Window->preferences: 2.选择General->keys; 3.在右侧中间的窗体中点击word compl ...

  2. 01scikit-learn数据集下载

    In [2]: from sklearn.datasets import load_iris iris = load_iris() iris.keys() Out[2]: dict_keys(['da ...

  3. linux man命令后面各种括号的意义

    圆括号 我们经常会看到 在说一个对象的man page 的时候,会有这样的格式: mmap(2) shm_open(3) 这个后面的数字是什么意思呢,通过 man man 命令就可以知道,这个是数字是 ...

  4. [php代码审计] Window api函数 FindFirstFile 在php中的问题

    include文件夹中文件: 内容: <?php echo __FILE__; ?> index.php: 演示如下: “<<”替换多个任意字符: “>”替换单个字符:

  5. 關於mac os系統的一些快捷鍵和操作

    一.了解mac os 1.桌面的组成元素 2.认识“Dock栏” Dock是一个神奇的东西,可以把Dock理解为Windows的任务栏,在这个地方可以随意拖放你想常驻在你屏幕底部的应用. Dock在工 ...

  6. 英国已有500万宽带用户接入并开始使用IPv6技术

    2018年英国首家为客户提供IPv6的主要ISP.随着所有现有的符合条件的用户线路启用,约90%的固定宽带用户群接入并开始使用IPv6,为IPv6互联网增加了超过500万个新眼球. 英国IPv6项目于 ...

  7. springCloud 服务提供者应返回的统一的数据格式

    package com.zledu.commonentity.entity; import lombok.AllArgsConstructor;import lombok.Data; import j ...

  8. [洛谷P2661] NOIP2015 信息传递

    问题描述 有 n 个同学(编号为 1 到 n)正在玩一个信息传递的游戏.在游戏里每人都有一个固定的信息传递对象,其中,编号为 i 的同学的信息传递对象是编号为 Ti 的同学. 游戏开始时,每人都只知道 ...

  9. Java浏览器弹出下载框,多个文件导出压缩包

    项目里一直有这个功能,也一直没怎么注意,今天研究了一下 依据逻辑往下走: 首先是要下载的ajax的Java方法,只有返回值需要设定一下,其他的不用管: Map<String, Object> ...

  10. Linux根据进程号查找其程序文件路径 及 lsof 命令使用

    查找进程文件路径 lsof -p pid 1.列出所有打开的文件: lsof 备注: 如果不加任何参数,就会打开所有被打开的文件,建议加上一下参数来具体定位 2. 查看谁正在使用某个文件 lsof   ...