Skip to content
Draft
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 @@ -57,6 +57,7 @@
import org.apache.fesod.sheet.util.WriteHandlerUtils;
import org.apache.fesod.sheet.write.handler.context.CellWriteHandlerContext;
import org.apache.fesod.sheet.write.handler.context.RowWriteHandlerContext;
import org.apache.fesod.sheet.write.handler.impl.StructuredTableWorkbookWriteHandler;
import org.apache.fesod.sheet.write.metadata.fill.AnalysisCell;
import org.apache.fesod.sheet.write.metadata.fill.FillConfig;
import org.apache.fesod.sheet.write.metadata.fill.FillWrapper;
Expand All @@ -66,6 +67,7 @@
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;

/**
* Fill the data into excel
Expand Down Expand Up @@ -108,8 +110,15 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor {
*/
private UniqueDataFlagKey currentUniqueDataFlag;

private final StructuredTableWorkbookWriteHandler structuredTableHandler;

public ExcelWriteFillExecutor(WriteContext writeContext) {
super(writeContext);
structuredTableHandler = writeContext.writeWorkbookHolder().getWriteHandlerList().stream()
.filter(StructuredTableWorkbookWriteHandler.class::isInstance)
.map(StructuredTableWorkbookWriteHandler.class::cast)
.findFirst()
.orElse(null);
}

public void fill(Object data, FillConfig fillConfig) {
Expand Down Expand Up @@ -142,6 +151,15 @@ public void fill(Object data, FillConfig fillConfig) {
if (CollectionUtils.isEmpty(collectionData)) {
return;
}
Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet();
if (structuredTableHandler != null && cachedSheet instanceof XSSFSheet) {
structuredTableHandler.prepareFill(
(XSSFSheet) cachedSheet,
analysisCellList,
collectionLastIndexCache.get(currentUniqueDataFlag),
fillConfig,
collectionData.size());
}
Iterator<?> iterator = collectionData.iterator();
if (WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection()) && fillConfig.getForceNewRow()) {
shiftRows(collectionData.size(), analysisCellList);
Expand Down Expand Up @@ -176,9 +194,6 @@ private void shiftRows(int size, List<AnalysisCell> analysisCellList) {
}
Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet();
int lastRowIndex = cachedSheet.getLastRowNum();
if (maxRowIndex >= lastRowIndex) {
return;
}
Sheet sheet = writeContext.writeSheetHolder().getCachedSheet();
int number = size;
if (collectionLastIndexMap == null) {
Expand All @@ -187,7 +202,11 @@ private void shiftRows(int size, List<AnalysisCell> analysisCellList) {
if (number <= 0) {
return;
}
sheet.shiftRows(maxRowIndex + 1, lastRowIndex, number, true, false);
if (structuredTableHandler != null && sheet instanceof XSSFSheet) {
structuredTableHandler.shiftRows((XSSFSheet) sheet, maxRowIndex, lastRowIndex, number);
} else if (maxRowIndex < lastRowIndex) {
sheet.shiftRows(maxRowIndex + 1, lastRowIndex, number, true, false);
}

// The current data is greater than unity rowindex increase
increaseRowIndex(templateAnalysisCache, number, maxRowIndex);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.apache.fesod.sheet.write.handler.impl.DimensionWorkbookWriteHandler;
import org.apache.fesod.sheet.write.handler.impl.EscapeHexCellWriteHandler;
import org.apache.fesod.sheet.write.handler.impl.FillStyleCellWriteHandler;
import org.apache.fesod.sheet.write.handler.impl.StructuredTableWorkbookWriteHandler;
import org.apache.fesod.sheet.write.handler.impl.WriteSheetWorkbookWriteHandler;
import org.apache.fesod.sheet.write.style.DefaultStyle;

Expand Down Expand Up @@ -59,6 +60,7 @@ public static List<WriteHandler> loadDefaultHandler(Boolean useDefaultStyle, Exc
List<WriteHandler> handlerList = new ArrayList<>();
switch (excelType) {
case XLSX:
handlerList.add(new StructuredTableWorkbookWriteHandler());
handlerList.add(new DimensionWorkbookWriteHandler());
handlerList.add(new DefaultRowWriteHandler());
handlerList.add(new EscapeHexCellWriteHandler());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/

package org.apache.fesod.sheet.write.handler.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.fesod.sheet.exception.ExcelGenerateException;
import org.apache.poi.ss.formula.FormulaParser;
import org.apache.poi.ss.formula.FormulaRenderer;
import org.apache.poi.ss.formula.FormulaShifter;
import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

final class StructuredTableFormulaShifter {
private StructuredTableFormulaShifter() {}

static Map<XSSFCell, String> shiftFormulas(
XSSFSheet movedSheet, int firstRow, int lastRow, int number, Map<XSSFTable, CellRangeAddress> ranges) {
XSSFWorkbook workbook = movedSheet.getWorkbook();
FormulaShifter shifter = FormulaShifter.createForRowShift(
workbook.getSheetIndex(movedSheet),
movedSheet.getSheetName(),
firstRow,
lastRow,
number,
workbook.getSpreadsheetVersion());
XSSFEvaluationWorkbook evaluationWorkbook = XSSFEvaluationWorkbook.create(workbook);
Set<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
for (Sheet sheet : workbook) {
for (XSSFTable table : ((XSSFSheet) sheet).getTables()) {
if (table.getName() != null) {
names.add(table.getName());
}
}
}
if (names.isEmpty()) {
return Collections.emptyMap();
}
Map<XSSFCell, String> formulas = new IdentityHashMap<>();
for (Sheet sheet : workbook) {
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() != CellType.FORMULA
|| !cell.getCellFormula().contains("[")) {
continue;
}
String shifted = shiftFormula((XSSFCell) cell, names, shifter, evaluationWorkbook, ranges);
if (shifted != null) {
formulas.put((XSSFCell) cell, shifted);
}
}
}
}
return formulas;
}

private static String shiftFormula(
XSSFCell cell,
Set<String> names,
FormulaShifter shifter,
XSSFEvaluationWorkbook workbook,
Map<XSSFTable, CellRangeAddress> ranges) {
String formula = cell.getCellFormula();
String marker = "__fesod_table_reference_";
while (formula.contains(marker)) {
marker += "_";
}
List<String> references = new ArrayList<>();
StringBuilder masked = new StringBuilder();
int copied = 0;
for (int index = 0; index < formula.length(); index++) {
char current = formula.charAt(index);
if (current == '"' || current == '\'') {
while (++index < formula.length()) {
if (formula.charAt(index) == current) {
if (index + 1 < formula.length() && formula.charAt(index + 1) == current) {
index++;
} else {
break;
}
}
}
} else if (current == '[') {
int start = index;
while (start > copied && isNameCharacter(formula.charAt(start - 1))) {
start--;
}
boolean qualified = names.contains(formula.substring(start, index));
boolean local = start == index && insideTable(cell, ranges);
if (!qualified && !local) {
continue;
}
int depth = 1;
int end = index + 1;
for (; end < formula.length() && depth > 0; end++) {
char character = formula.charAt(end);
if (character == '\'') {
end++;
} else if (character == '[') {
depth++;
} else if (character == ']') {
depth--;
}
}
if (depth != 0) {
throw new ExcelGenerateException("Unbalanced structured table reference: " + formula);
}
if (!qualified
&& end < formula.length()
&& (isNameCharacter(formula.charAt(end)) || formula.charAt(end) == '!')) {
continue;
}
masked.append(formula, copied, start)
.append('"')
.append(marker)
.append(references.size())
.append('"');
references.add(formula.substring(start, end));
copied = end;
index = end - 1;
}
}
if (references.isEmpty()) {
return null;
}
masked.append(formula, copied, formula.length());
int sheetIndex = cell.getSheet().getWorkbook().getSheetIndex(cell.getSheet());
// Mask only table expressions so POI can move A1 references without expanding tables into A1 ranges.
Ptg[] tokens =
FormulaParser.parse(masked.toString(), workbook, FormulaType.CELL, sheetIndex, cell.getRowIndex());
if (!shifter.adjustFormula(tokens, sheetIndex)) {
return formula;
}
String shifted = FormulaRenderer.toFormulaString(workbook, tokens);
for (int index = 0; index < references.size(); index++) {
shifted = shifted.replace('"' + marker + index + '"', references.get(index));
}
return shifted;
}

private static boolean isNameCharacter(char character) {
return Character.isLetterOrDigit(character) || character == '_' || character == '.' || character == '\\';
}

private static boolean insideTable(XSSFCell cell, Map<XSSFTable, CellRangeAddress> ranges) {
for (XSSFTable table : cell.getSheet().getTables()) {
CellRangeAddress range = ranges.get(table);
if (range == null) {
range = CellRangeAddress.valueOf(table.getCTTable().getRef());
}
if (range.isInRange(cell.getRowIndex(), cell.getColumnIndex())) {
return true;
}
}
return false;
}
}
Loading
Loading