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


    导航

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

    上一篇:ExcelReport源码解析

    概述

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

    示例

    1)谈谈新需求:

    image

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

    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(@"TemplateTemplate.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(@"TemplateTemplate.xls", saveFileDlg.FileName,
        new SheetFormatterContainer("Sheet1", formatters));

    4)测试结果:

    image

    源码下载:

    image

  • 相关阅读:
    约合¥1720 LG法国称G Watch将于6月开卖
    c语言中的位移位操作
    兼容的动态加载JS【原】
    Oracle 10g AND Oracle 11g手工建库案例--Oracle 10g
    面向对象思想----不看懊悔!
    学习设计模式--观察者模式(C++)
    使用POI 导入excel
    机器学习 F1-Score, recall, precision
    阿里无线11.11:手机淘宝移动端接入网关基础架构演进之路
    ICE 迁移64位安装问题
  • 原文地址:https://www.cnblogs.com/hanzhaoxin/p/4248086.html
Copyright © 2020-2023  润新知