Home » excel » excel – How to duplicate main loop data within JETT?

excel – How to duplicate main loop data within JETT?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m developing Excel report with hierarchy data.
Using JETT (java excel template translator) and I’d like to duplicate rows from the main loop when there are collection of collection. Here is a brief example.

public class JettTest {
    @Test
    public void run() throws IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream template = classLoader.getResourceAsStream("template.xlsx");
        try (
                XSSFWorkbook wb = new XSSFWorkbook(template);
                FileOutputStream fos = new FileOutputStream("target/output.xlsx")
        ) {
            Map<String, Object> params = new HashMap<>();
            Parent parent1 = new Parent("parent1", Arrays.asList("child1", "child2"));
            Parent parent2 = new Parent("parent2", Arrays.asList("childX", "childY"));
            List<Parent> parents = Arrays.asList(parent1, parent2);
            params.put("parents", parents);

            ExcelTransformer transformer = new ExcelTransformer();
            transformer.transform(wb, params);
            wb.write(fos);
        }
    }

    public class Parent {
        private String name;
        private List<String> children;

        public Parent(String name, List<String> children) {
            this.name = name;
            this.children = children;
        }

        public String getName() {
            return name;
        }

        public List<String> getChildren() {
            return children;
        }
    }
}

Excel template is

template

A1 is

<jt:forEach items="${parents}" var="parent">${parent.name}

B1 is

<jt:forEach items="${parent.children}" var="child">${child}</jt:forEach></jt:forEach>

This gives me

actual

It looks good, however, I need to duplicate parent names and get

enter image description here

Any ideas, please?

How to&Answers:

You’ll need {parent.name} to be within the child forEach tag if you want the parent name to be displayed for each child name.

What happens if you move the child forEach tag from B1 to A1, right after the parent forEach tag?