change files location

This commit is contained in:
STS
2020-07-03 23:56:52 +02:00
parent be5c52bd3b
commit 8f22ea5d36
6 changed files with 4 additions and 120 deletions
@@ -0,0 +1,34 @@
package com.baeldung.poi.excel.setFormula;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.util.List;
public class ExcelFormula {
XSSFWorkbook excel;
public XSSFSheet inserData(List<Integer> dataList) {
excel = new XSSFWorkbook();
XSSFSheet sheet = excel.createSheet();
int rowNum =0 ;
for (Integer data : dataList){
sheet.createRow(rowNum++).createCell(0).setCellValue(data);
}
return sheet;
}
public double setFormula(String formula) throws IOException {
XSSFSheet sheet = excel.getSheetAt(0);
int lastCellNum = sheet.getRow(0).getLastCellNum();
XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum + 1);
formulaCell.setCellFormula(formula);
XSSFFormulaEvaluator formulaEvaluator = excel.getCreationHelper().createFormulaEvaluator();
CellValue evaluate = formulaEvaluator.evaluate(formulaCell);
if(excel != null)
excel.close();
return evaluate.getNumberValue();
}
}
@@ -0,0 +1,29 @@
package com.baeldung.poi.excel.setFormula;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
class ExcelFormulaUnitTest {
@Test
void givenExcelData_whenSetAndEvaluateFormula() throws IOException {
ExcelFormula excelFormula = new ExcelFormula();
List<Integer> data = Arrays.asList(2, 5, 10, 15, 7, 9);
XSSFSheet sheet = excelFormula.inserData(data);
int result = 0;
for (int row = 0; row <= sheet.getLastRowNum(); row++) {
result += sheet.getRow(row).getCell(0).getNumericCellValue();
}
String colName = CellReference.convertNumToColString(0);
String startCell = colName + 1;
String stopCell = colName + (sheet.getLastRowNum() + 1);
String sumFormula = String.format("SUM(%s:%s)", startCell, stopCell);
int resultValue = (int) excelFormula.setFormula(sumFormula);
Assert.assertEquals("The results are the same!", resultValue , result);
}
}