ExcelBuilder.java

  1. package no.nav.data.common.export;

  2. import no.nav.data.common.exceptions.TechnicalException;
  3. import org.docx4j.openpackaging.packages.SpreadsheetMLPackage;
  4. import org.docx4j.openpackaging.parts.PartName;
  5. import org.docx4j.openpackaging.parts.SpreadsheetML.WorksheetPart;
  6. import org.xlsx4j.jaxb.Context;
  7. import org.xlsx4j.sml.CTRst;
  8. import org.xlsx4j.sml.CTXstringWhitespace;
  9. import org.xlsx4j.sml.ObjectFactory;
  10. import org.xlsx4j.sml.STCellType;

  11. import java.io.ByteArrayOutputStream;

  12. public class ExcelBuilder {

  13.     public static final String SPREADSHEETML_SHEET_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  14.     private static final ObjectFactory fac = Context.getsmlObjectFactory();

  15.     private final SpreadsheetMLPackage pack;
  16.     private final WorksheetPart sheet;

  17.     long rowN = 0;

  18.     public ExcelBuilder(String sheetName) {
  19.         try {
  20.             pack = SpreadsheetMLPackage.createPackage();
  21.             sheet = pack.createWorksheetPart(new PartName("/xl/worksheets/sheet1.xml"), sheetName, 1);
  22.         } catch (Exception e) {
  23.             throw new TechnicalException("excel error", e);
  24.         }
  25.     }

  26.     public ExcelRow addRow() {
  27.         return new ExcelRow();
  28.     }

  29.     public class ExcelRow {

  30.         org.xlsx4j.sml.Row row = fac.createRow();
  31.         char col = 'A';

  32.         public ExcelRow() {
  33.             row.setR(++rowN);
  34.             sheet.getJaxbElement().getSheetData().getRow().add(row);
  35.         }

  36.         public ExcelRow addCell(String content) {
  37.             var cell = fac.createCell();

  38.             CTXstringWhitespace t = fac.createCTXstringWhitespace();
  39.             t.setValue(content);
  40.             CTRst ctRst = fac.createCTRst();
  41.             ctRst.setT(t);

  42.             cell.setIs(ctRst);
  43.             cell.setR("%s%s".formatted(col++, rowN));
  44.             cell.setT(STCellType.INLINE_STR);
  45.             row.getC().add(cell);
  46.             return this;
  47.         }

  48.         public ExcelRow addCell(Number number) {
  49.             var cell = fac.createCell();

  50.             cell.setV(number != null ? String.valueOf(number) : "");
  51.             cell.setR("%s%s".formatted(col++, rowN));
  52.             cell.setT(STCellType.N);
  53.             row.getC().add(cell);
  54.             return this;
  55.         }

  56.     }

  57.     public byte[] build() {
  58.         try {
  59.             var outStream = new ByteArrayOutputStream();
  60.             pack.save(outStream);
  61.             return outStream.toByteArray();
  62.         } catch (Exception e) {
  63.             throw new TechnicalException("excel error", e);
  64.         }
  65.     }
  66. }