ExcelReport Article 3: Extended element formatter and excelreport Article 3
Navigation
Contents: NPOI-based report engine-ExcelReport
Previous Article: ExcelReport source code analysis Overview
The architecture of ExcelRepor has been introduced in the previous article. This article describes how to extend the element formatter to meet more requirements through examples.
Example 1) New Requirements:
A cell contains multiple parameters.
2) implementation code:
PartFormatter. cs:
/*
Class: PartFormatter
Description: Cell local (element) formatter.
Coder: Han Zhao new date: January 25, 2015
Modification record:
*/
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 inherits ElementFormatter and implements the Format method ).
3) test code:
// Instantiate a parameter container and load the template filling rule File
ParameterCollection collection = new ParameterCollection();
collection.Load(@"Template\Template.xml");
// Instantiate an element formatter list
List<ElementFormatter> formatters = new List<ElementFormatter>();
Formatters. Add (new PartFormatter (collection ["Sheet1", "Dept"], "Dept", "physical "));
Formatters. Add (new PartFormatter (collection ["Sheet1", "Class"], "Class", "mechanics 1 "));
// Export the file to a local device
Export.ExportToLocal(@"Template\Template.xls", saveFileDlg.FileName,
new SheetFormatterContainer("Sheet1", formatters));
4) test results:
Download source code:
: Https://github.com/hanzhaoxin/ExcelReport