/
javapractice
/
JavaPractice
Обзор
Документация
Войти
/
javapractice
/
JavaPractice
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
2
CI/CD
Аналитика
develop
ApachePOI/src/main/java/utils/XLSXSaver.java
139 строк
6 KB
Zexa91x0
Apache POI - XLSXSave
24 май 2021, 18:47
24 май 2021, 18:47
6bf1dfc
Код
Авторство
О чём код?
package utils; import entities.Owner; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Name; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; public class XLSXSaver { public static void exportToNewXLSX(AllocationsDB allocationsDB, String newFilePath) throws IOException { XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("CellPhones"); namedField(allocationsDB, wb, "UserName", "CellPhones!$A$1:$A$"); // создать именованный диапазон "Amount" namedField(allocationsDB, wb, "Amount", "CellPhones!$F$1:$F$"); // создание именованного диапазона "Limit" namedField(allocationsDB, wb, "Limit", "CellPhones!$I$1:$I$"); // создать именованный диапазон "UserTotal" namedField(allocationsDB, wb, "UserTotal", "CellPhones!$H$1:$H$"); // заполняем ее данными AtomicInteger nextRowNumber = new AtomicInteger(); allocationsDB.getAllocationStream().forEach(allocation -> { XSSFRow row = sheet.createRow(nextRowNumber.get()); row.createCell(0, CellType.STRING).setCellValue( allocation.getOwnersList().stream() .map(Owner::getComment) .collect(Collectors.joining("; ")) ); row.createCell(1, CellType.STRING).setCellValue( allocation.getOwnersList().stream() .findFirst().get().getDepartment().getOrganizationUnit() ); row.createCell(2, CellType.STRING).setCellValue( allocation.getOwnersList().stream() .findFirst().get().getDepartment().getDepartment()); row.createCell(3, CellType.STRING).setCellValue( allocation.getOwnersList().stream() .findFirst().get().getDepartment().getFunctional()); row.createCell(4, CellType.STRING).setCellValue( allocation.getCellPhone().getNumber()); if (allocation.getAmount() > 0) row.createCell(5, CellType.NUMERIC).setCellValue( allocation.getAmount()); row.createCell(6, CellType.STRING).setCellValue( allocation.getCellPhone().getOperator()); row.createCell(7, CellType.FORMULA).setCellFormula( "SUMIF(UserName,UserName,Amount)"); row.createCell(8, CellType.NUMERIC).setCellValue( allocation.getOwnersList().stream() .findFirst().get().getLimit()); // XSSFCell cell9 - формула перерасход // =IF([@Limit]-[@[UserTotal]]<0; [@Limits]-[@[UserTotal]]; \"\");"); // =IF([@Limits]-[@[общая по сотруднику]]<0; [@Limits]-[@[общая по сотруднику]];"") row.createCell(9, CellType.FORMULA).setCellFormula( "IF((Limit-UserTotal)<0, (Limit-UserTotal), 0)"); // "SUM(Limit, CellPhones!$H$1)"); row.createCell(10, CellType.STRING).setCellValue( allocation.getCellPhone().getType().name()); row.createCell(11, CellType.STRING).setCellValue( allocation.getCellPhone().getComment()); row.createCell(12, CellType.STRING).setCellValue( allocation.getCellPhone().getICCID()); nextRowNumber.getAndIncrement(); }); // выравнивание столбца по размеру данных for (int i = 0; i <= 11; i++) { sheet.autoSizeColumn(i); } /* // 4. create named formula Name namedFormula = wb.createName(); namedFormula.setNameName("Owerdrive"); namedFormula.setRefersToFormula("SUM(CellPhones!$1$1:$6$1)");*/ /* // получить данные из именованного диапазона по имени диапазона Name aNamedCell = wb.getName("Limit"); AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula(), EXCEL2007); CellReference[] crefs = aref.getAllReferencedCells(); for (int i = 0; i < crefs.length; i++) { Sheet s = wb.getSheet(crefs[i].getSheetName()); Row r = sheet.getRow(crefs[i].getRow()); Cell c = r.getCell(crefs[i].getCol()); System.out.println(c.getNumericCellValue()); } */ // записываем книгу в новый файл екселя OutputStream fileOut = new FileOutputStream(newFilePath); wb.write(fileOut); } /** * создание именованного диапазона UserName * @param allocationsDB - телефоны * @param wb - рабочая книга * @param fieldName - диапазон ячеек * @param s */ private static Name namedField(AllocationsDB allocationsDB, XSSFWorkbook wb, String fieldName, String s) { // Name namedArray = wb.createName(); namedArray.setNameName(fieldName); namedArray.setRefersToFormula(s + allocationsDB.getAllocations().size()); return namedArray; } }