ExcelReport第三篇:扩展元素格式化器

导航

目   录:基于NPOI的报表引擎——ExcelReport

上一篇:ExcelReport源码解析

概述

上篇中已介绍了ExcelRepor的架构,本篇将通过例子讲述如何扩展元素格式化器以满足更多的需求。

示例

1)谈谈新需求:

ExcelReport第三篇:扩展元素格式化器

如图所示,一个单元格内包含多个参数。

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)测试结果:

ExcelReport第三篇:扩展元素格式化器

源码下载:

ExcelReport第三篇:扩展元素格式化器

上一篇:Log4j扩展使用--日志记录器Logger


下一篇:Log4j扩展使用--自定义输出