Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.vaadin.flow.component.ComponentUtil;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.Grid.Column;
import com.vaadin.flow.component.grid.HeaderRow;
import com.vaadin.flow.component.grid.dataview.GridLazyDataView;
import com.vaadin.flow.data.provider.AbstractBackEndDataProvider;
import com.vaadin.flow.data.provider.DataCommunicator;
Expand Down Expand Up @@ -89,14 +90,54 @@ protected Stream<T> getDataStream(Query newQuery) {
return stream;
}

protected List<Pair<String, Column<T>>> getGridHeaders(Grid<T> grid) {
return exporter.getColumnsOrdered().stream()
.map(
column ->
ImmutablePair.of(
renderCellTextContent(grid, column, GridExporter.COLUMN_HEADER), column))
.collect(Collectors.toList());
}
protected List<Pair<List<String>, Column<T>>> getGridHeaders(Grid<T> grid) {
return exporter.getColumnsOrdered().stream()
.map(column -> ImmutablePair.of(getHeaderTexts(grid, column), column))
.collect(Collectors.toList());
}

private List<String> getHeaderTexts(Grid<T> grid, Column<T> column) {
List<String> headerTexts = new ArrayList<>();

List<HeaderRow> headerRows = grid.getHeaderRows();
for (HeaderRow headerRow : headerRows) {
String headerText = renderCellTextContent(grid, column, GridExporter.COLUMN_HEADER, headerRow);
headerTexts.add(headerText);
}

return headerTexts;
}

private String renderCellTextContent(Grid<T> grid, Column<T> column, String columnType, HeaderRow headerRow) {
String headerOrFooter = (String) ComponentUtil.getData(column, columnType);

if (Strings.isBlank(headerOrFooter)) {
Function<Column<?>, Component> getHeaderOrFooterComponent;
if (GridExporter.COLUMN_HEADER.equals(columnType)) {
getHeaderOrFooterComponent = col -> col.getHeaderComponent();
headerOrFooter = column.getHeaderText();
} else if (GridExporter.COLUMN_FOOTER.equals(columnType)) {
getHeaderOrFooterComponent = col -> col.getFooterComponent();
headerOrFooter = column.getFooterText();
} else {
throw new IllegalArgumentException();
}

if (Strings.isBlank(headerOrFooter)) {
try {
Component component = getHeaderOrFooterComponent.apply(column);
if (component != null) {
headerOrFooter = component.getElement().getTextRecursively();
}
} catch (RuntimeException e) {
throw new IllegalStateException(
"Problem when trying to render header or footer cell text content", e);
}
}
}

return headerOrFooter;
}

protected List<Pair<String, Column<T>>> getGridFooters(Grid<T> grid) {
return exporter.getColumnsOrdered().stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,10 @@ protected XWPFDocument createDoc() throws IOException {
cctblgridcol, "" + Math.round(9638 / exporter.getColumns().size()));
});

List<Pair<String, Column<T>>> headers = getGridHeaders(exporter.grid);
List<Pair<String, Column<T>>> headers = getGridHeaders(exporter.grid).stream()
.map(pair ->
Pair.of(pair.getLeft().get(0), pair.getRight())
).toList();
XWPFTableCell cell = findCellWithPlaceHolder(table, exporter.headersPlaceHolder);
if (cell != null) {
fillHeaderOrFooter(table, cell, headers, true, exporter.headersPlaceHolder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
Expand Down Expand Up @@ -94,16 +95,20 @@ public InputStream createInputStream() {
}

Cell cell = findCellWithPlaceHolder(sheet, exporter.headersPlaceHolder);
List<Pair<String, Column<T>>> headers = getGridHeaders(exporter.grid);
List<Pair<List<String>, Column<T>>> headersTest = getGridHeaders(exporter.grid);
List<Pair<String, Column<T>>> headers = headersTest.stream()
.map(pair ->
Pair.of(pair.getLeft().get(0), pair.getRight())
).toList();

fillHeaderOrFooter(sheet, cell, headers, true);
fillHeaderOrFooter(sheet, cell, headersTest, true);
if (exporter.autoMergeTitle && titleCell != null) {
sheet.addMergedRegion(
new CellRangeAddress(
titleCell.getRowIndex(),
titleCell.getRowIndex(),
titleCell.getColumnIndex(),
titleCell.getColumnIndex() + headers.size() - 1));
titleCell.getColumnIndex() + headersTest.size() - 1));
}

cell = findCellWithPlaceHolder(sheet, exporter.dataPlaceHolder);
Expand All @@ -126,7 +131,7 @@ public InputStream createInputStream() {
cell = findCellWithPlaceHolder(sheet, exporter.footersPlaceHolder);
List<Pair<String, Column<T>>> footers = getGridFooters(exporter.grid);
if (cell != null) {
fillHeaderOrFooter(sheet, cell, footers, false);
fillFooter(sheet, cell, footers, false);
}

if (exporter.isAutoSizeColumns()) {
Expand Down Expand Up @@ -440,39 +445,54 @@ private Cell findCellWithPlaceHolder(Sheet sheet, String placeholder) {
return null;
}

private void fillHeaderOrFooter(
Sheet sheet,
Cell headersOrFootersCell,
List<Pair<String, Column<T>>> headersOrFooters,
boolean isHeader) {
private void fillFooter(Sheet sheet, Cell headersOrFootersCell,
List<Pair<String, Column<T>>> headersOrFooters, boolean isHeader) {

List<Pair<List<String>, Column<T>>> headersOrFootersCellSingleRow = headersOrFooters.stream()
.map(pair -> Pair.of(List.of(pair.getLeft()), pair.getRight())).toList();
fillHeaderOrFooter(sheet, headersOrFootersCell, headersOrFootersCellSingleRow, isHeader);
}

private void fillHeaderOrFooter(Sheet sheet, Cell headersOrFootersCell,
List<Pair<List<String>, Column<T>>> headersOrFooters, boolean isHeader) {

CellStyle style = headersOrFootersCell.getCellStyle();
sheet.setActiveCell(headersOrFootersCell.getAddress());
headersOrFooters.forEach(
headerOrFooter -> {
if (!isHeader) {
// clear the styles before processing the column in the footer
ComponentUtil.setData(headerOrFooter.getRight(), COLUMN_CELLSTYLE_MAP, null);
}
Cell cell =
sheet
.getRow(sheet.getActiveCell().getRow())
.getCell(sheet.getActiveCell().getColumn());
if (cell == null) {
cell =
sheet
.getRow(sheet.getActiveCell().getRow())
.createCell(sheet.getActiveCell().getColumn());
}
cell.setCellStyle(style);
Object value =
(isHeader
? headerOrFooter.getLeft()
: transformToType(headerOrFooter.getLeft(), headerOrFooter.getRight()));
buildCell(value, cell, headerOrFooter.getRight(), null);
configureAlignment(headerOrFooter.getRight(), cell, isHeader?ExcelCellType.HEADER:ExcelCellType.FOOTER);
sheet.setActiveCell(
new CellAddress(
sheet.getActiveCell().getRow(), sheet.getActiveCell().getColumn() + 1));
});

int startRow = headersOrFootersCell.getRowIndex();
int currentColumn = headersOrFootersCell.getColumnIndex();

for (Pair<List<String>, Column<T>> headerOrFooter : headersOrFooters) {
List<String> headerTexts = headerOrFooter.getLeft();
Column<T> column = headerOrFooter.getRight();

if (!isHeader) {
ComponentUtil.setData(column, COLUMN_CELLSTYLE_MAP, null);
}

sheet.shiftRows(startRow, sheet.getLastRowNum(), headerTexts.size());

for (int i = 0; i < headerTexts.size(); i++) {
Row row = sheet.getRow(startRow + i);
if (row == null) {
row = sheet.createRow(startRow + i);
}

Cell cell = row.getCell(currentColumn);
if (cell == null) {
cell = row.createCell(currentColumn);
}

cell.setCellStyle(style);

Object value =
(isHeader ? headerTexts.get(i) : transformToType(headerTexts.get(i), column));
buildCell(value, cell, column, null);

configureAlignment(column, cell, isHeader ? ExcelCellType.HEADER : ExcelCellType.FOOTER);
}

currentColumn++;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public GridExporterDemoView() {
addDemo(GridExporterCustomColumnsDemo.class);
addDemo(GridExporterHierarchicalDataDemo.class);
addDemo(GridExporterBigDatasetDemo.class);
addDemo(GridExporterMultipleHeaderRowsDemo.class);
setSizeFull();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*-
* #%L
* Grid Exporter Add-on
* %%
* Copyright (C) 2022 - 2023 Flowing Code
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.flowingcode.vaadin.addons.gridexporter;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.apache.poi.EncryptedDocumentException;

import com.flowingcode.vaadin.addons.demo.DemoSource;
import com.github.javafaker.Faker;
import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.Grid.Column;
import com.vaadin.flow.component.grid.HeaderRow;
import com.vaadin.flow.component.grid.HeaderRow.HeaderCell;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.data.provider.DataProvider;
import com.vaadin.flow.data.renderer.LitRenderer;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;

@DemoSource
@PageTitle("Grid Exporter Addon Multiple Header Rows Demo")
@Route(value = "gridexporter/headers", layout = GridExporterDemoView.class)
@SuppressWarnings("serial")
public class GridExporterMultipleHeaderRowsDemo extends Div {

public GridExporterMultipleHeaderRowsDemo() throws EncryptedDocumentException, IOException {
Grid<Person> grid = new Grid<>(Person.class);
DecimalFormat decimalFormat = new DecimalFormat("$#,###.##");
grid.removeAllColumns();
grid.addColumn(
LitRenderer.<Person>of("<b>${item.name}</b>").withProperty("name", Person::getName))
.setHeader("Name");
grid.addColumn("lastName").setHeader("Last Name");
grid.addColumn(item -> Faker.instance().lorem().characters(30, 50)).setHeader("Big column");
Column<Person> budgetColumn =
grid.addColumn(item -> decimalFormat.format(item.getBudget()))
.setHeader("Budget")
.setTextAlign(ColumnTextAlign.END);
BigDecimal[] total = new BigDecimal[1];
total[0] = BigDecimal.ZERO;
Stream<Person> stream =
IntStream.range(0, 100)
.asLongStream()
.mapToObj(
number -> {
Faker faker = new Faker();
Double budget = faker.number().randomDouble(2, 10000, 100000);
total[0] = total[0].add(BigDecimal.valueOf(budget));
budgetColumn.setFooter(new DecimalFormat("$#,###.##").format(total[0]));
return new Person(
faker.name().firstName(),
(Math.random() > 0.3 ? faker.name().lastName() : null),
faker.number().numberBetween(15, 50),
budget);
});

grid.setItems(DataProvider.fromStream(stream));
grid.setWidthFull();
this.setSizeFull();

HeaderRow firstExtraHeaderRow = grid.appendHeaderRow();
HeaderRow secondExtraHeaderRow = grid.appendHeaderRow();
for (Column<Person> column : grid.getColumns()) {
String columnHeader = grid.getHeaderRows().get(0).getCell(column).getText();

HeaderCell firstHeaderCell = firstExtraHeaderRow.getCell(column);
firstHeaderCell.setComponent(new Span(columnHeader + " 1"));
HeaderCell secondHeaderCell = secondExtraHeaderRow.getCell(column);
secondHeaderCell.setComponent(new Span(columnHeader + " 2"));
}

GridExporter<Person> exporter =
GridExporter.createFor(grid, "/custom-template.xlsx", "/custom-template.docx");
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("${date}", new SimpleDateFormat().format(Calendar.getInstance().getTime()));
exporter.setAdditionalPlaceHolders(placeholders);
exporter.setSheetNumber(1);
exporter.setCsvExportEnabled(false);
exporter.setNumberColumnFormat(budgetColumn, decimalFormat, "$#,###.##");
exporter.setTitle("People information");
exporter.setNullValueHandler(() -> "(No lastname)");
exporter.setFileName(
"GridExport" + new SimpleDateFormat("yyyyddMM").format(Calendar.getInstance().getTime()));
add(grid);
}
}
9 changes: 9 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { UserConfigFn } from 'vite';
import { overrideVaadinConfig } from './vite.generated';

const customConfig: UserConfigFn = (env) => ({
// Here you can add custom Vite parameters
// https://vitejs.dev/config/
});

export default overrideVaadinConfig(customConfig);
Loading