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

功效:支持对excel文档的汇入汇出,图表(excel自带的图表基本都可以实现)的列印
源代码下载:https://github.com/caofangsheng93/ExcelExportInMvc
安装:NuGet
导出思路:

准备:

1.创建对象

namespace Models
{
    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; }
    }
}

1.创建Excel帮助类

using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace Common
{
    /// <summary>
    /// Excel导出帮助类
    /// </summary>
    public class ExcelExportHelper
    {
        public static string ExcelContentType => "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;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add($"{heading}Data");
                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 = 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(data), heading, isShowSlNo, columnsToTake);
        }
}
}

3.获取数据并显示

//数据类
using Models;
using System.Collections.Generic;
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},
        };
    }
}

//用于显示的数据类
using BLL;
using Models;
using System.Collections.Generic;
namespace EPPlusMvcDemo2.Models
{
    public class StudentViewModel
    {
        public List<Student> ListStudent => StaticDataOfStudent.ListStudent;
    }
}

实现部分:

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.视图

@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

转载于:https://www.cnblogs.com/zhang1f/p/11093679.html

C# 使用Epplus导出数据到Excel相关推荐

  1. java导出为excel文件_java导出数据到excel文件

    有的时候,将一些有用的数据导出到excel是很有必要的.比如说,我现在在做一个学校的在线教学平台,有一个需求是:将学生成绩导出到excel文件中去. 那怎样实现用java导出数据到excel文件呢?? ...

  2. 百度指数常见php框架,怎么导出数据到excel表格-如何将百度指数数据导出到Excel表格...

    如何将百度指数数据导出到Excel表格 第一步:打开CAD.CAD命令行输入"Li"."选择对象"选需要提取坐标的多段线.回车. 第二步:将CAD文本框中的数据 ...

  3. arcengine遍历属性表_【程序之坑】小程序云开发导出数据到excel表

    本文解决了小程序云开发导出数据到excel的bug,并给出了分析的过程,同时简化了程序为一个云函数,一个本地函数,逻辑更简单.文章结尾给出了完整源代码 小程序云开发为没有服务器的小程序开发者提供了便利 ...

  4. python输出数据到excel-python如何导出数据到excel文件

    python导出数据到excel文件的方法: 1.调用Workbook()对象中的add_sheet()方法wb = xlwt.Workbook() ws = wb.add_sheet('A Test ...

  5. python输出数据到excel-Python从数据库导出数据到Excel

    #coding=utf-8 import pymysql import xlwt import importlib,sys importlib.reload(sys) # __author__ = ' ...

  6. (转)另一篇:VC导出数据到EXCEL

    另一篇:VC导出数据到EXCEL 2010-08-28 17:03:47|  分类: 默认分类 |  标签: |字号大中小 订阅 我们制作应用软件的时候,经常要把结果以报表的形式输出,当前使用较为广泛 ...

  7. SQLSERVER使用CLR Stored Procedure导出数据到Excel

    在实际应用中,我们经常需要导出数据到Excel文件,你可以使用DTS或SSIS来做.但有时,我们并不需要这么重量级的工具,直接用CLR SP实现就可以了. 假设你已经写好了导出Excel的C# cod ...

  8. 前端利用JS导出数据到Excel表 数字是文本类型 无法计算

    问题描述:前端利用JS导出数据到Excel表 数字是文本类型 无法进行公式计算:前端利用JS导出数据到Excel表 数字是文本类型 无法计算 解决办法:参考https://bbs.csdn.net/t ...

  9. spring boot实现导出数据到excel

    1.导入依赖; <!--数据导出依赖 excel--> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --&g ...

最新文章

  1. 织梦生成html加速,加快DEDECMS静态html网页生成速度的方法
  2. Java8初体验(二)Stream语法详解(转)
  3. 使用谷歌身份验证器增强SSH安全
  4. 【深度学习】449页pdf,FaceBook称其迈出“重塑AI科学的第一步”
  5. STL 之fill和fill_n
  6. 【转】Docker 容器化核心概念
  7. html页面按钮删除一条数据库,需要添加一个删除按钮到一个HTML表格从数据库中删除记录与消息...
  8. QML Profiler性能优化教程
  9. 参数名称 java_java – 具有重要名称的WSDL中的参数名称
  10. 【GRE协议】CentOS配置GRE隧道
  11. 美团优选、多多买菜等五家社区团购被罚650万元;打车手机越贵,接单车型越贵;微软推出低代码语言 Power Fx | 极客头条...
  12. 中兴获25个5G商用合同
  13. python中的元组字符串整数浮点数都是不可变的数据类型,Python不可变数据类型总结...
  14. DOA算法1:MUSIC算法(一)
  15. pip卸载pillow时的报错解决
  16. matlab把数据乘,【excel怎么相乘】如何把EXCLE数据导入到MATLAB中
  17. 操作抖音取名项目日赚 500 实战案例分析
  18. Excel2003和Excel2007的区别
  19. 带自动还原魔方游戏源码
  20. 商业智能BI的价值,可视化报表等于商业智能BI吗?

热门文章

  1. 2018年第九届蓝桥杯C/C++ C组国赛 —— 第三题:全排列
  2. oracle里返回值吗,Oracle有返回值的存储过程 | 学步园
  3. python coding_Python终极coding
  4. Codeforces 991E. Bus Number (DFS+排列组合)
  5. php+循环定时任务,php定时任务循环执行replace操作无故中断
  6. html(1)基本组成
  7. linux写一个脚本杀进程,linux下如何自动检测并重新启动一个死掉的进程,然后再把它杀死:)(shell脚本实现)...
  8. zephyr 系统--- 内存池使用方法
  9. Px4源码框架结构图
  10. 13.transform确保目标空间足够大