目 录:基于NPOI的报表引擎——ExcelReport
上一篇:ExcelReport源码解析
上篇中已介绍了ExcelRepor的架构,本篇将通过例子讲述如何扩展元素格式化器以满足更多的需求。

如图所示,一个单元格内包含多个参数。
PartFormatter.cs:
monospace; width: 100%; border-bottom-style: none; color: black; padding-bottom: 0px; direction: ltr; text-align: left; padding-top: 0px; border-right-style: none; padding-left: 0px; margin: 0em; border-left-style: none; line-height: 12pt; padding-right: 0px; background-color: white">/* 类: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方法)。
//实例化一个参数容器,并加载模板填充规则文件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));


下载地址:https://github.com/hanzhaoxin/ExcelReport