C# 使用Epplus导出Excel [2]:导出动态列数据
C# 使用Epplus导出Excel [1]:导出固定列数据
C# 使用Epplus导出Excel [2]:导出动态列数据
C# 使用Epplus导出Excel [3]:合并列连续相同数据
上一篇导出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 = ; i < headerTexts.Length; i++)
{
AddHeader(sheet, i + , 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[, columnIndex].Value = headerText;
sheet.Cells[, 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 = ; i < items.Count; i++)
{
for (var j = ; j < propertySelectors.Length; j++)
{
sheet.Cells[i + startRowIndex, j + ].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 = ; i < headerTextsDictionary.Length; i++)
{
AddHeader(sheet, i + + 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 = ; i < items.Count; i++)
{
for (var j = ; j < dictionaryKeys.Count; j++)
{
sheet.Cells[i + startRowIndex, j + + 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 = ; i < ; i++)
{
Student s = new Student();
s.Code = "c" + i;
s.Name = "n" + i;
studentList.Add(s);
} //获得不固定数据
for (int i = ; 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[].Dictionarys); if (studentList.Count > )
{
for (int i = ; 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, , studentList, columnsValueList.ToArray());
if (studentList.Count > )
{
//添加动态表头
EpplusHelper.AddHeader(worksheet, columnsNameList.ToArray(), columnsNameDictionaryList.ToArray());
//添加动态数据
EpplusHelper.AddObjects(worksheet, , studentList, columnsValueList.ToArray(), dictionaryKeys);
}
package.Save();
}
完整代码详情请移步我的github:https://github.com/gordongaogithub/ExportDictionaryExcelByEpplus.git
C# 使用Epplus导出Excel [2]:导出动态列数据的更多相关文章
- 一个通用的DataGridView导出Excel扩展方法(支持列数据格式化)
假如数据库表中某个字段存放的值“1”和“0”分别代表“是”和“否”,要在DataGridView中显示“是”和“否”,一般用两种方法,一种是在sql中直接判断获取,另一种是在DataGridView的 ...
- 使用Apache POI导出Excel小结--导出XLS格式文档
使用Apache POI导出Excel小结 关于使用Apache POI导出Excel我大概会分三篇文章去写 使用Apache POI导出Excel小结--导出XLS格式文档 使用Apache POI ...
- Excel中的一列数据变成文本的一行数据
Excel中的一列数据变成文本的一行数据 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/
- winform导入导出excel,后台动态添加控件
思路: 导入: 1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();) 2, 获取用户选择文件的后缀名(s ...
- 导出Excel And 导出word
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx. ...
- 分享使用NPOI导出Excel树状结构的数据,如部门用户菜单权限
大家都知道使用NPOI导出Excel格式数据 很简单,网上一搜,到处都有示例代码. 因为工作的关系,经常会有处理各种数据库数据的场景,其中处理Excel 数据导出,以备客户人员确认数据,场景很常见. ...
- java实现导出Excel(跨行,跨列)
先来个最终结果样式: 第一步: 传参,后期可根据自己需要进行调整.我这里需要的是 quarter 代表季度 dptid 部门编号根据接受过来的参数进行文档命名. UserInfo userInfo=( ...
- java导出Excel定义导出模板
在很多系统功能中都会有Excel导入导出功能,小编采用JXLS工具,简单.灵活. JXLS是基于 Jakarta POI API 的Excel报表生成工具,它采用标签的方式,类似于jsp页面的EL表达 ...
- java导出excel时合并同一列中相同内容的行
一.有时候导出Excel时需要按类别导出,一大类下好几个小类,小类下又有好几个小小类,就像下图: 要实现这个也不难, 思路如下:按照大类来循环,如上就是按照张江校区.徐汇校区.临港校区三个大类循环,然 ...
随机推荐
- Java反编译工具JD-GUI以及Eclipse的反编译插件
什么是反编译 高级语言源程序经过编译变成可执行文件,反编译就是逆过程.但是通常不能把可执行文件变成高级语言源代码,只能转换成汇编程序. 反编译是一个复杂的过程,所以越是高级语言,就越难于反编译,但目前 ...
- Cstring的使用
https://msdn.microsoft.com/zh-cn/aa315043 1.字符串提取函数,CString::Left.CString::Mid .CString::Right CStri ...
- linux常用命令(ubuntu)
编辑: vi [path] vim [path] :q 退出 :wq 保存退出 查看进程 ps ps -aux | grep mem 查看全部含 “mem”的进程 ps –aux 查看全部 在系统启 ...
- Python及bs4、lxml、numpy模块包的安装
http://blog.csdn.net/tiantiancsdn/article/details/51046490(转载) Python及bs4.lxml.numpy模块包的安装 Python 的安 ...
- [ZJOI2008]无序运动Movement
Description D博士对物理有着深入的研究,经典物理.天体物理.量子物理都有着以他的名字命名的定理.最近D博士着迷于研究粒子运动的无规则性.对圣经深信不疑的他相信,上帝创造的任何事物必然是有序 ...
- springMVC-RESTful支持
RESTful支持 什么是restful? Restful就是一个资源定位及资源操作的风格.不是标准也不是协议,只是一种风格,是对http协议的诠释. 资源定位:互联网所有的事物都是资源,要求url中 ...
- CentOS 7.4升级curl和git到最新版本
升级curl和git到最新版本 [root@jenkins ~]# yum install -y curl-devel expat-devel gettext-devel openssl-devel ...
- LVDT
什么是 LVDT? LVDT 是线性可变差动变压器的缩写. 它是一种常见类型的机电传感器,可将其以机械方式耦合的物体的直线运动转换为对应的电气信号.LVDT 线性位移传感器随时可用,可以测量各种移动, ...
- SpringBoot 2.x (9):整合Mybatis注解实战
SSM框架再熟悉不过了,不过以前通常是使用XML写SQL语句 这里用SpringBoot整合Mybatis并且使用注解进行开发 依赖: <!-- Mybatis --> <depen ...
- @RequestParam和@ResponseBody注解的区别(转)
@RequestParam 用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容.(Http协议中,如果不指定Content-Type, ...