C# 使用Epplus导出Excel [1]:导出固定列数据

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

C# 使用Epplus导出Excel [3]:合并列连续相同数据

C# 使用Epplus导出Excel [4]:合并指定行

C# 使用Epplus导出Excel [5]:样式

上一篇导出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]:导出动态列数据的更多相关文章

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

    假如数据库表中某个字段存放的值“1”和“0”分别代表“是”和“否”,要在DataGridView中显示“是”和“否”,一般用两种方法,一种是在sql中直接判断获取,另一种是在DataGridView的 ...

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

    使用Apache POI导出Excel小结 关于使用Apache POI导出Excel我大概会分三篇文章去写 使用Apache POI导出Excel小结--导出XLS格式文档 使用Apache POI ...

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

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

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

    思路: 导入: 1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();) 2, 获取用户选择文件的后缀名(s ...

  5. 导出Excel And 导出word

      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx. ...

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

    大家都知道使用NPOI导出Excel格式数据 很简单,网上一搜,到处都有示例代码. 因为工作的关系,经常会有处理各种数据库数据的场景,其中处理Excel 数据导出,以备客户人员确认数据,场景很常见. ...

  7. java实现导出Excel(跨行,跨列)

    先来个最终结果样式: 第一步: 传参,后期可根据自己需要进行调整.我这里需要的是 quarter 代表季度 dptid 部门编号根据接受过来的参数进行文档命名. UserInfo userInfo=( ...

  8. java导出Excel定义导出模板

    在很多系统功能中都会有Excel导入导出功能,小编采用JXLS工具,简单.灵活. JXLS是基于 Jakarta POI API 的Excel报表生成工具,它采用标签的方式,类似于jsp页面的EL表达 ...

  9. java导出excel时合并同一列中相同内容的行

    一.有时候导出Excel时需要按类别导出,一大类下好几个小类,小类下又有好几个小小类,就像下图: 要实现这个也不难, 思路如下:按照大类来循环,如上就是按照张江校区.徐汇校区.临港校区三个大类循环,然 ...

随机推荐

  1. Integrative Analysis of MicroRNAome, Transcriptome, and Proteome during the Limb Regeneration of Cynops orientalis (文献分享一组-翁海玉)

    文献名:Integrative Analysis of MicroRNAome, Transcriptome, and Proteome during the Limb Regeneration of ...

  2. 新建Podfile命令

    接下来,你需要建立一个主工程.建立成功以后,再次启动终端, 利用cd命令进入到工程文件夹内,此时需要创建一个特殊的文本文件,命令如下: 命令: touch Podfile 创建 命令: open -e ...

  3. pycharm中模块matplolib生成图表出现中文乱码解决方法

    在python文件中加入如下两行 import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中 ...

  4. 升级log4j到log4j2报错:cannot access org.apache.http.annotation.NotThreadSafe

    问题与分析 今天把项目的log4j的依赖改成了log4j2的依赖后,发现使用Maven打包时报错如下: [ERROR] Failed to execute goal org.apache.maven. ...

  5. 《Python网络爬虫相关基础概念》

    爬虫介绍 引入 之前在授课过程中,好多同学都问过我这样的一个问题:为什么要学习爬虫,学习爬虫能够为我们以后的发展带来那些好处?其实学习爬虫的原因和为我们以后发展带来的好处都是显而易见的,无论是从实际的 ...

  6. 转 载python数据分析(1)-numpy产生随机数

    转自:http://blog.csdn.net/jinxiaonian11/article/details/53143141 在数据分析中,数据的获取是第一步,numpy.random 模块提供了非常 ...

  7. 牛客小白月赛13 E(图、矩阵幂)

    AC通道 如果建立第一天某点到某点有几条路的矩阵,做k次矩阵乘就是第k天某点到某点有几条路.统计即可. #include <bits/stdc++.h> using namespace s ...

  8. C. Divide by Three DP

    http://codeforces.com/contest/792/problem/C 这题奇葩题我居然用dp过了. 如果要模拟的话,可以用一个栈保存,保存每一个%3 = 2的pos,%3 = 1的p ...

  9. G. Of Zorcs and Axes 二分 + 贪心 —— STL的用法

    http://codeforces.com/gym/101149/problem/G 一开始还以为要用二分图去做,但是复杂度也太高了,O(n * m)的话直接爆炸. 考虑贪心,考虑第i个东西优先选一个 ...

  10. php中socket的使用(重点参考)

    一.开启socket phpinfo();查看是否开启了socket扩展,否则在php.ini中开启. 二.服务器端代码的写法 <?php error_reporting(E_ALL); set ...