ExcelStamper.java
package pro.verron.officestamper.experimental;
import org.docx4j.openpackaging.packages.SpreadsheetMLPackage;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.xlsx4j.sml.CTRst;
import pro.verron.officestamper.api.OfficeStamper;
import pro.verron.officestamper.api.OfficeStamperException;
import static pro.verron.officestamper.experimental.Placeholders.findVariables;
/// The ExcelStamper class is an implementation of the OfficeStamper interface for stamping Excel templates. It uses the
/// DOCX4J library to manipulate the template and replace variable expressions with values from the context.
public class ExcelStamper
implements OfficeStamper<SpreadsheetMLPackage> {
/// Default constructor for the ExcelStamper class. This constructor initializes an instance of the ExcelStamper
/// class, which implements the OfficeStamper interface for processing and stamping Excel templates. The class
/// manipulates templates by replacing variable expressions with values from a given context.
public ExcelStamper() {
// Explicit default constructor to hold javadoc
}
@Override
public SpreadsheetMLPackage stamp(SpreadsheetMLPackage template, Object context)
throws OfficeStamperException {
var paragraphs = ExcelCollector.collect(template, CTRst.class);
for (CTRst cell : paragraphs) {
var paragraph = new ExcelParagraph(cell);
var string = paragraph.asString();
for (var variable : findVariables(string)) {
var expression = variable.expression();
var evaluationContext = new StandardEvaluationContext(context);
var parserConfiguration = new SpelParserConfiguration();
var parser = new SpelExpressionParser(parserConfiguration);
var parsedExpression = parser.parseExpression(variable.content());
var value = parsedExpression.getValue(evaluationContext);
var stringValue = String.valueOf(value);
paragraph.replace(expression, stringValue);
}
}
return template;
}
}