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. Python scrapy框架爬取瓜子二手车信息数据

    项目实施依赖: python,scrapy ,fiddler scrapy安装依赖的包: 可以到https://www.lfd.uci.edu/~gohlke/pythonlibs/  下载 pywi ...

  2. Git - .gitignore怎么忽略已经被版本控制的文件

    问题 如果某个文件已经存在于远程仓库了,也就是说某个文件已经被版本控制了,如果将该文件添加到.gitignore中,是无法生效的.因为.gitignore是用来控制尚未被纳入版本控制的文件,如果文件已 ...

  3. 两段代码实现vue路由懒加载

    const Foo = () => import('./Foo.vue') const router = new VueRouter({ routes: [ { path: '/foo', co ...

  4. tinymce 富文本简单使用

    tinymce.init({ //选择器 selector:'textarea', //配置顶部的菜单栏显示隐藏 menubar: false, //配置中文(默认没有中文包,需要到官网下载,放到la ...

  5. YII报错笔记:<pre>PHP Notice &#039;yii\base\ErrorException&#039; with message &#039;Uninitialized string offset: 0&#039; in /my/test/project/iot/vendor/yiisoft/yii2/base/Model.php:778

    YII常见报错笔记 报错返回的代码如下: <pre>PHP Notice 'yii\base\ErrorException' with message 'Uninitialized str ...

  6. centOS 7联网

    在windows上安装的centOS7虚拟机要联网后才能正常使用,只需这样配置下即可: 打开vim /etc/sysconfig/network-scripts/ifcfg-eno16777736,会 ...

  7. robot framework 在pycharm中语法无法高亮显示的,显示绿色解决办法(Robot Framework with PyCharm)

    Robot Framework with PyCharm up vote1down votefavorite 1 I am totally new to automation and trying t ...

  8. 18113 Secret Book of Kungfu 按位DFS

    http://acm.scau.edu.cn:8000/uoj/mainMenu.html 18113 Secret Book of Kungfu 该题有题解 时间限制:1000MS  内存限制:65 ...

  9. 生产环境中mysql+keepalive双主模式,keepalive守护进程实现双主切换提供数据库服务

    mysql+keepalive实现浮动地址自动切换,由于keepalive无自带健康检查功能,所以必须自动编写健康检查守护进程(监控DB1和DB2数据库的监控状态,来保证浮动地址双机自动切换.) 一, ...

  10. js获取select下拉框选项的值

    var onchange="getBatch(this.options[this.options.selectedIndex].value)"