C# 使用Epplus导出Excel [2]:导出动态列数据

上一篇导出excel,是导出已知固定列,有时候我们根本就不知道有几列、列名是什么,因此这些动态列,可以用Dictionary<string,string>接收。

1、实体Student上加上一个字段Dictionarys

Student.cs

 public class Student
    {
        public String Name { get; set; }

        public String Code { get; set; }

        public Dictionary<string, string> Dictionarys { get; set; }
    }

2、表头表体类上加上动态列的添加表头与表体

EpplusHelper.cs

public static class EpplusHelper
    {

        /// <summary>
        /// 添加表头
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="headerTexts"></param>
        public static void AddHeader(ExcelWorksheet sheet, params string[] headerTexts)
        {
            for (var i = 0; i < headerTexts.Length; i++)
            {
                AddHeader(sheet, i + 1, headerTexts[i]);
            }
        }

        /// <summary>
        /// 添加表头
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="columnIndex"></param>
        /// <param name="headerText"></param>
        public static void AddHeader(ExcelWorksheet sheet, int columnIndex, string headerText)
        {
            sheet.Cells[1, columnIndex].Value = headerText;
            sheet.Cells[1, columnIndex].Style.Font.Bold = true;
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="startRowIndex"></param>
        /// <param name="items"></param>
        /// <param name="propertySelectors"></param>
        public  static void AddObjects(ExcelWorksheet sheet, int startRowIndex, IList<Student> items, Func<Student, object>[] propertySelectors)
        {
            for (var i = 0; i < items.Count; i++)
            {
                for (var j = 0; j < propertySelectors.Length; j++)
                {
                    sheet.Cells[i + startRowIndex, j + 1].Value = propertySelectors[j](items[i]);
                }
            }
        }

        /// <summary>
        /// 添加动态表头
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="headerTexts"></param>
        /// <param name="headerTextsDictionary"></param>
        public  static void AddHeader(ExcelWorksheet sheet, string[] headerTexts, string[] headerTextsDictionary)
        {
            for (var i = 0; i < headerTextsDictionary.Length; i++)
            {
                AddHeader(sheet, i + 1 + headerTexts.Length, headerTextsDictionary[i]);
            }
        }

        /// <summary>
        /// 添加动态数据
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="startRowIndex"></param>
        /// <param name="items"></param>
        /// <param name="propertySelectors"></param>
        /// <param name="dictionaryKeys"></param>

        public static void AddObjects(ExcelWorksheet sheet, int startRowIndex, IList<Student> items, Func<Student, object>[] propertySelectors, List<string> dictionaryKeys)
        {
            for (var i = 0; i < items.Count; i++)
            {
                for (var j = 0; j < dictionaryKeys.Count; j++)
                {
                    sheet.Cells[i + startRowIndex, j + 1 + propertySelectors.Length].Value = items[i].Dictionarys[dictionaryKeys[j]];
                }
            }

        }

        public static List<String> GetDictionaryKeys(Dictionary<string, string> dics)
        {
            List<string> resultList = new List<string>();
            foreach (KeyValuePair<string, string> kvp in dics)
            {
                resultList.Add(kvp.Key);
            }
            return resultList;
        }

    }

3、修改Main方法,导出Excel

主要代码如下:

 //获得数据
            List<Student> studentList = new List<Student>();
            for (int i = 0; i < 10; i++)
            {
                Student s = new Student();
                s.Code = "c" + i;
                s.Name = "n" + i;
                studentList.Add(s);
            }

            //获得不固定数据
            for (int i = 0; i < studentList.Count; i++)
            {
                Dictionary<string, string> dictionarys = new Dictionary<string, string>();
                dictionarys.Add("D1", "d1" + i);
                dictionarys.Add("D2", "d2" + i);
                studentList[i].Dictionarys = dictionarys;
            }

            //创建excel
            string fileName = @"d:\" + "导出excel" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
            FileInfo newFile = new FileInfo(fileName);
            using (ExcelPackage package = new ExcelPackage(newFile))
            {
                #region 固定列
                List<ExcelExportDto<Student>> excelExportDtoList = new List<ExcelExportDto<Student>>();
                excelExportDtoList.Add(new ExcelExportDto<Student>("Code", _ => _.Code));
                excelExportDtoList.Add(new ExcelExportDto<Student>("Name", _ => _.Name));

                List<string> columnsNameList = new List<string>();
                List<Func<Student, object>> columnsValueList = new List<Func<Student, object>>();
                foreach (var item in excelExportDtoList)
                {
                    columnsNameList.Add(item.ColumnName);
                    columnsValueList.Add(item.ColumnValue);
                }

                #endregion

                #region 不固定列
                List<ExcelExportDto<Dictionary<string, string>>> excelExportDictionaryDtoList = new List<ExcelExportDto<Dictionary<string, string>>>();
                List<string> columnsNameDictionaryList = new List<string>();
                List<string> dictionaryKeys = EpplusHelper.GetDictionaryKeys(studentList[0].Dictionarys);

                if (studentList.Count > 0)
                {
                    for (int i = 0; i < dictionaryKeys.Count; i++)
                    {
                        var index = i;
                        excelExportDictionaryDtoList.Add(new ExcelExportDto<Dictionary<string, string>>(dictionaryKeys[i], _ => _.FirstOrDefault(q => q.Key == dictionaryKeys[i]).Value));
                    }
                    foreach (var item in excelExportDictionaryDtoList)
                    {
                        columnsNameDictionaryList.Add(item.ColumnName);
                    }
                }
                #endregion

                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Test");
                worksheet.OutLineApplyStyle = true;
                //添加表头
                EpplusHelper.AddHeader(worksheet, columnsNameList.ToArray());
                //添加数据
                EpplusHelper.AddObjects(worksheet, 2, studentList, columnsValueList.ToArray());
                if (studentList.Count > 0)
                {
                    //添加动态表头
                    EpplusHelper.AddHeader(worksheet, columnsNameList.ToArray(), columnsNameDictionaryList.ToArray());
                    //添加动态数据
                    EpplusHelper.AddObjects(worksheet, 2, studentList, columnsValueList.ToArray(), dictionaryKeys);
                }
                package.Save();
            }

完整代码详情请移步我的github:https://github.com/gordongaogithub/ExportDictionaryExcelByEpplus.git

原文地址:https://www.cnblogs.com/jishugaochao/p/10345794.html

时间: 2024-08-08 05:18:08

C# 使用Epplus导出Excel [2]:导出动态列数据的相关文章

一个通用的DataGridView导出Excel扩展方法(支持列数据格式化)

假如数据库表中某个字段存放的值“1”和“0”分别代表“是”和“否”,要在DataGridView中显示“是”和“否”,一般用两种方法,一种是在sql中直接判断获取,另一种是在DataGridView的CellFormatting事件中设置.下面介绍的是第二种情况下的处理.举个例子,DataGridView的第4列需要在金额后面加个“元”,在第14列根据1和0显示为相应的是和否,在显示的时候可以这样设置: http://blog.csdn.net/gdjlc/article/details/158

使用Apache POI导出Excel小结--导出XLS格式文档

使用Apache POI导出Excel小结 关于使用Apache POI导出Excel我大概会分三篇文章去写 使用Apache POI导出Excel小结--导出XLS格式文档 使用Apache POI导出Excel小结--导出XLSX格式文档 使用Apache POI导出Excel--大数量导出 导出XLS格式文档 做企业应用项目难免会有数据导出到Excel的需求,最近在使用其,并对导出Excel封装成工具类开放出来供大家参考.关于Apache POI Excel基本的概念与操作我在这里就不啰嗦

Excel导入DataTable兼容2003-2012(请细心查看注释)以及 DataTable导出Excel(导出格式2003.xls)注释:需要引用NPOI

1.#region Excel导入DataTable兼容2003-2012(请细心查看注释)/// <summary> /// 读取Excel文件到DataSet中/// 注释1:2012导出如报错“ System.InvalidOperationException: 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序.”解决:下载2007 Office system 驱动程序:数据连接组件安装http://download.microsoft.com/downl

Excel中的一列数据变成文本的一行数据

Excel中的一列数据变成文本的一行数据 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 原文地址:https://www.cnblogs.com/kailugaji/p/10867312.html

winform导入导出excel,后台动态添加控件

思路: 导入: 1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();) 2, 获取用户选择文件的后缀名(string extension = Path.GetExtension(fileDialog.FileName).ToLower();),并设置允许后缀文件名: 3,NPOI转datetable,遍历tatetable转成实体类列表并入库: 导出: 1, 创建提示用户保存类,SaveFileDial

分享使用NPOI导出Excel树状结构的数据,如部门用户菜单权限

大家都知道使用NPOI导出Excel格式数据 很简单,网上一搜,到处都有示例代码. 因为工作的关系,经常会有处理各种数据库数据的场景,其中处理Excel 数据导出,以备客户人员确认数据,场景很常见. 一个系统开发出来,系统要运行起来,很多数据要初始化,这个时候也是需要客户提供各种业务的基础数据.客户提供的数据中,其中除了word.pdf,最常见的就是Excel. 废话不多说,直接上图上代码: 如图, 左侧三列,作为 一个系统 所有菜单的树状结构. 其他列 以用户的信息(如用户名.登录名) 作为表

C#导出EXCEL(DataTable导出EXCEL)

using System; using System.Collections.Generic; using System.Text; using System.Data; using System.IO; using System.Web; using Microsoft.Office.Interop.Excel; using System.Reflection; /*  * 开发人员:Hisen  * 时间:2008年11月24日  * 功能:将数据导出Excel  *  */ namespa

使用jxl 工具类 导出Excel 单行导出

一.jxl工具类 package com.zsplat.qrcode.commons.utils; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List;

excel中同行多列数据的比较

大家在工作中经常遇到对同一行的单元进行比较,在这种情况下都会怎么去做呢?其实对于比较单元格数据,excel有中方法.大家首先看一下我们要进行比较的数据,以同行两列为例. a1 和b1的比较,我们在c1 用公式 =a1=a2 即可; a2 和b2 的比较,我们同样用=a2=b2, 大家注意到,其实这两个单元格中的数据严格来讲是不同的,但公式返回的也是TRUE.这就得出一个结论,用等号来比较两个单元格是不区分大小写的.如果要区分大小写,就需要用exact()函数 a3和b3  a4和b4 数字是没有