Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix xlsx formatting #176

Merged
merged 3 commits into from
Dec 12, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ plugins {
}

group 'com.docutools'
version = '1.5.7-alpha.1'
version = '1.5.9-alpha.1'

sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -401,6 +402,8 @@ private Optional<PlaceholderData> resolveSimplePlaceholder(Object property, Stri
} else if (property instanceof Path path && isFieldAnnotatedWith(bean.getClass(), placeholderName, Image.class)) {
return ReflectionUtils.findFieldAnnotation(bean.getClass(), placeholderName, Image.class)
.map(image -> new ImagePlaceholderData(path).withMaxWidth(image.maxWidth()));
} else if (property instanceof UUID uuid) {
return Optional.of(new ScalarPlaceholderData<>(uuid.toString()));
} else {
return Optional.empty();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,13 @@ public class SXSSFWriter implements ExcelWriter {
/**
* Maps the {@link CellStyle} objects of the old workbook to the new ones.
*/
private final Map<CellStyle, CellStyle> styleStyleMapping = new HashMap<>();
private final Map<Integer, CellStyle> cellStyleMap = new HashMap<>();
private Sheet currentSheet;
private Sheet templateSheet;
private Row currentRow;
private int rowOffset = 0;
private int leftMostColumn = -1;
private int rightMostColumn = -1;

/**
* Creates a new SXSSFWriter.
Expand Down Expand Up @@ -102,6 +105,7 @@ private static void transferPicture(XSSFShape shape, SXSSFSheet newSheet) {
@Override
public void newSheet(Sheet sheet) {
logger.info("Creating new sheet of {}", sheet.getSheetName());
templateSheet = sheet;
currentSheet = workbook.createSheet(sheet.getSheetName());
currentSheet.setActiveCell(sheet.getActiveCell());
currentSheet.setAutobreaks(sheet.getAutobreaks());
Expand Down Expand Up @@ -139,19 +143,55 @@ public void newRow(Row row) {
logger.debug("Creating new row {}", row.getRowNum());
currentRow = currentSheet.createRow(row.getRowNum() + rowOffset);
currentRow.setHeight(row.getHeight());
currentRow.setRowStyle(row.getRowStyle());
if (row.isFormatted()) {
currentRow.setRowStyle(cellStyleMap.computeIfAbsent((int) row.getRowStyle().getIndex(), i -> copyCellStyle(row.getRowStyle())));
}
currentRow.setZeroHeight(row.getZeroHeight());
updateColumnStyles(row);
}

private void updateColumnStyles(Row row) {
AntonOellerer marked this conversation as resolved.
Show resolved Hide resolved
if (rightMostColumn == -1 || leftMostColumn == -1) {
setup(row);
}
if (row.getLastCellNum() > rightMostColumn) {
for (; rightMostColumn < row.getLastCellNum(); rightMostColumn++) {
copyColumnStyle(rightMostColumn);
}
logger.debug("Rightmost column: {}", rightMostColumn);
}
if (row.getFirstCellNum() < leftMostColumn) {
for (; leftMostColumn > row.getLastCellNum(); leftMostColumn--) {
copyColumnStyle(leftMostColumn);
}
logger.debug("Leftmost column: {}", leftMostColumn);
}
}

private void setup(Row row) {
leftMostColumn = row.getFirstCellNum();
rightMostColumn = row.getLastCellNum();
logger.debug("Rightmost column: {}", rightMostColumn);
logger.debug("Leftmost column: {}", leftMostColumn);
for (int i = leftMostColumn; i < rightMostColumn; i++) {
copyColumnStyle(i);
}
}

private void copyColumnStyle(int rightMostColumn) {
CellStyle columnStyle = templateSheet.getColumnStyle(rightMostColumn);
if (columnStyle != null) {
currentSheet.setDefaultColumnStyle(rightMostColumn,
cellStyleMap.computeIfAbsent((int) columnStyle.getIndex(), i -> copyCellStyle(columnStyle)));
}
}

@Override
public void addCell(Cell cell) {
logger.debug("Creating new cell {} {}", cell.getColumnIndex(), cell.getRow().getRowNum());
logger.trace("Creating new cell {} {}", cell.getColumnIndex(), cell.getRow().getRowNum());
var newCell = currentRow.createCell(cell.getColumnIndex(), cell.getCellType());
if (workbook.getCellStyleAt(cell.getCellStyle().getIndex()) == null) {
copyCellStyle(cell.getCellStyle());
}
newCell.setCellComment(cell.getCellComment());
newCell.setCellStyle(cell.getCellStyle());
newCell.setCellStyle(cellStyleMap.computeIfAbsent((int) cell.getCellStyle().getIndex(), i -> copyCellStyle(cell.getCellStyle())));
newCell.setHyperlink(cell.getHyperlink());
currentSheet.setColumnWidth(cell.getColumnIndex(), cell.getSheet().getColumnWidth(cell.getColumnIndex()));
switch (cell.getCellType()) {
Expand All @@ -162,6 +202,7 @@ public void addCell(Cell cell) {
case BOOLEAN -> newCell.setCellValue(cell.getBooleanCellValue());
case ERROR -> newCell.setCellErrorValue(cell.getErrorCellValue());
default -> {
// do nothing
}
}
if (cell.getHyperlink() != null) {
Expand All @@ -180,11 +221,11 @@ public void addCell(Cell templateCell, String newCellText) {

@Override
public void addCell(Cell templateCell, String newCellText, int columnOffset) {
logger.debug("Creating new cell {} {} with text {}",
logger.trace("Creating new cell {} {} with text {}",
templateCell.getColumnIndex(), templateCell.getRow().getRowNum(), newCellText);
var newCell = currentRow.createCell(templateCell.getColumnIndex() + columnOffset, templateCell.getCellType());
newCell.setCellComment(templateCell.getCellComment());
newCell.setCellStyle(styleStyleMapping.computeIfAbsent(templateCell.getCellStyle(), this::copyCellStyle));
newCell.setCellStyle(cellStyleMap.computeIfAbsent((int) templateCell.getCellStyle().getIndex(), i -> copyCellStyle(templateCell.getCellStyle())));
newCell.setHyperlink(templateCell.getHyperlink());
currentSheet.setColumnWidth(templateCell.getColumnIndex(), templateCell.getSheet().getColumnWidth(templateCell.getColumnIndex()));
if (templateCell.getCellType() == CellType.FORMULA) {
Expand Down
10 changes: 10 additions & 0 deletions src/test/java/com/docutools/jocument/ReflectionResolvingTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -274,4 +274,14 @@ void shouldTranslateShipName() {

assertThat(shipName.get().toString(), equalTo("VSS Unternehmung"));
}

@Test
void shouldResolveUUIDtoString() {
Person picardPerson = SampleModelData.PICARD_PERSON;
var resolver = new ReflectionResolver(picardPerson);

var id = resolver.resolve("id");

assertThat(id.get().toString(), equalTo(picardPerson.getId().toString()));
}
}
20 changes: 19 additions & 1 deletion src/test/java/com/docutools/jocument/excel/ExcelDocuments.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,25 @@ void shouldResolveNestedLoops() throws InterruptedException, IOException {
void inherti() throws InterruptedException, IOException {
// Arrange
Template template = Template.fromClassPath("/templates/excel/Formatting.xlsx")
.orElseThrow();
.orElseThrow();
PlaceholderResolver resolver = new ReflectionResolver(SampleModelData.PICARD);

// Act
Document document = template.startGeneration(resolver);
document.blockUntilCompletion(60000L); // 1 minute

// Assert
assertThat(document.completed(), is(true));

Desktop.getDesktop().open(document.getPath().toFile());
}

@Test
@DisplayName("Inherit style from source excel.")
void inheritStylePerCell() throws InterruptedException, IOException {
// Arrange
Template template = Template.fromClassPath("/templates/excel/ComplexFormatting.xlsx")
.orElseThrow();
PlaceholderResolver resolver = new ReflectionResolver(SampleModelData.PICARD);

// Act
Expand Down
6 changes: 6 additions & 0 deletions src/test/java/com/docutools/jocument/sample/model/Person.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneOffset;
import java.util.UUID;

public class Person {
private final UUID id = UUID.randomUUID();

private final String firstName;
private final String lastName;
Expand Down Expand Up @@ -55,4 +57,8 @@ public void setFavouriteShip(Ship favouriteShip) {
public Ship getFavouriteShip() {
return favouriteShip;
}

public UUID getId() {
return id;
}
}
Binary file not shown.