ExcelReport第三篇:扩展元素格式化器
生活随笔
收集整理的这篇文章主要介绍了
ExcelReport第三篇:扩展元素格式化器
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
2019独角兽企业重金招聘Python工程师标准>>>
导航
目 录:基于NPOI的报表引擎——ExcelReport
上一篇:ExcelReport源码解析
概述
上篇中已介绍了ExcelRepor的架构,本篇将通过例子讲述如何扩展元素格式化器以满足更多的需求。
示例
1)谈谈新需求:
如图所示,一个单元格内包含多个参数。
2)实现代码:
PartFormatter.cs:
/* 类:PartFormatter 描述:单元格局部(元素)格式化器 编 码 人:韩兆新 日期:2015年01月25日 修改记录: */ using System.Drawing; using NPOI.SS.UserModel; namespace ExcelReport { public class PartFormatter:ElementFormatter { private Point _cellPoint; private string _parameterName; private string _value; public PartFormatter(Point cellPoint, string parameterName ,string value) { this._cellPoint = cellPoint; this._parameterName = parameterName; this._value = value; } public override void Format(SheetFormatterContext context) { var rowIndex = context.GetCurrentRowIndex(_cellPoint.X); var row = context.Sheet.GetRow(rowIndex); if (null == row) { row = context.Sheet.CreateRow(rowIndex); } var cell = row.GetCell(_cellPoint.Y); if (null == cell) { cell = row.CreateCell(_cellPoint.Y); } if (cell.CellType.Equals(CellType.String)) { SetCellValue(cell, cell.StringCellValue.Replace(string.Format("$[{0}]", _parameterName), _value)); } } } }(PartFormatter继承ElementFormatter,实现Format方法)。
3)测试代码:
//实例化一个参数容器,并加载模板填充规则文件 ParameterCollection collection = new ParameterCollection(); collection.Load(@"Template\Template.xml"); //实例化一个元素格式化器列表 List<ElementFormatter> formatters = new List<ElementFormatter>(); formatters.Add(new PartFormatter(collection["Sheet1", "Dept"],"Dept","物理")); formatters.Add(new PartFormatter(collection["Sheet1", "Class"], "Class", "力学一")); //导出文件到本地 Export.ExportToLocal(@"Template\Template.xls", saveFileDlg.FileName, new SheetFormatterContainer("Sheet1", formatters));4)测试结果:
源码下载:
下载地址:https://github.com/hanzhaoxin/ExcelReport
转载于:https://my.oschina.net/hanzhaoxin/blog/373278
总结
以上是生活随笔为你收集整理的ExcelReport第三篇:扩展元素格式化器的全部内容,希望文章能够帮你解决所遇到的问题。