码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-25 13:46:00      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

导航

目   录:基于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)测试结果:

技术分享

 

源码下载:

技术分享

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

标签:

原文地址:http://www.cnblogs.com/hanzhaoxin/p/4248086.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!