JXLS, XLSWriter 추가

master
mjkhan21 11 months ago
parent 0f467b4158
commit 815ac2676e

@ -0,0 +1,15 @@
package cokr.xit.base.file;
import java.io.OutputStream;
public interface Downloadable {
String getFilename();
String getContentType();
String getDisposition();
Number getLength();
void write(OutputStream out);
}

@ -1,229 +0,0 @@
package cokr.xit.base.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.function.Consumer;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;
import cokr.xit.foundation.AbstractComponent;
import cokr.xit.foundation.data.StringMap;
/**
* @author mjkhan
*/
public class XLS extends AbstractComponent {
/**엑셀 파일(*.xlsx)의 mime type */
public static final String MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/** (row) Functional interface
* @author mjkhan
* @param <E> (row)
*/
@FunctionalInterface
public static interface Writer<E> {
/** (row) .
* @param sheet
* @param element (row)
* @param index . 0
*/
void write(XSSFSheet sheet, E element, int index);
}
/** .
* @param cell
* @return
*/
public static Object getValue(Cell cell) {
switch (cell.getCellType()) {
case STRING: return cell.getStringCellValue();
case NUMERIC: return cell.getNumericCellValue();
case BOOLEAN: return cell.getBooleanCellValue();
case BLANK: return "";
default: return null;
}
}
/** .
* @param cell Cell
* @param value
*/
public static void setValue(Cell cell, Object value) {
if (isEmpty(value)) {
cell.setCellValue("");
return;
}
if (value instanceof String) {
cell.setCellValue((String)value);
} else if (value instanceof Number) {
Number number = (Number)value;
cell.setCellValue(number.doubleValue());
} else if (value instanceof Date) {
cell.setCellValue((Date)value);
} else if (value instanceof Boolean) {
Boolean b = (Boolean)value;
cell.setCellValue(b.booleanValue());
} else
throw new IllegalArgumentException(value.getClass().getName() + ": " + value);
}
private StringMap<CellStyle> styles;
public void setValue(String key, Cell cell, Object value) {
setValue(cell, value);
if (styles == null)
styles = new StringMap<>();
CellStyle style = styles.get(key);
if (style == null)
styles.put(key, style = cell.getCellStyle());
cell.setCellStyle(style);
}
/** String .
* @param cell
* @return
*/
public static String getString(Cell cell) {
Object value = getValue(cell);
return isEmpty(value) ? ""
: value instanceof String ? (String)value
: value.toString();
}
/** Number .
* @param cell
* @return
* <ul><li> </li>
* <li> 0</li>
* </ul>
*/
public static Number getNumber(Cell cell) {
Object value = getValue(cell);
return isEmpty(value) ? 0
: value instanceof Number ? (Number)value
: value instanceof String ? Double.parseDouble((String)value)
: 0;
}
/** Boolean .
* @param cell
* @return
* <ul><li> Boolean</li>
* <li> false</li>
* </ul>
*/
public static Boolean getBoolean(Cell cell) {
Object value = getValue(cell);
return isEmpty(value) ? false
: value instanceof Boolean ? (Boolean)value
: Boolean.valueOf(value.toString());
}
private XSSFWorkbook workbook;
/**FileInputStream .
* @param input FileInputStream
* @return XLS
*/
public XLS load(FileInputStream input) {
try {
workbook = new XSSFWorkbook(input);
return this;
} catch (Exception e) {
throw applicationException(e);
}
}
/** .
* @param path . classpath:..., file:...
* @return XLS
*/
public XLS load(String path) {
try (FileInputStream input = new FileInputStream(ResourceUtils.getFile(path))) {
return load(input);
} catch (Exception e) {
throw applicationException(e);
}
}
/** .
* @return
*/
public XSSFWorkbook getWorkbook() {
return ifEmpty(workbook, () -> workbook = new XSSFWorkbook());
}
/** .
* @param index . 0
* @return
*/
public XSSFSheet getWorksheet(int index) {
int count = getWorkbook().getNumberOfSheets();
return index < count ? workbook.getSheetAt(index) : workbook.createSheet();
}
/** .
* @param sheetIndex . 0
* @param reader row Function
* @return XLS
*/
public XLS read(int sheetIndex, Consumer<Row> reader) {
if (reader == null) return this;
XSSFSheet worksheet = getWorksheet(sheetIndex);
for (Row row: worksheet) {
reader.accept(row);
}
return this;
}
/** dataset row .
* @param sheetIndex . 0
* @param dataset
* @param writer dataset row Function
* @return XLS
*/
public <E, T extends Iterable<E>> XLS write(int sheetIndex, T dataset, Writer<E> writer) {
XSSFSheet worksheet = getWorksheet(sheetIndex);
if (!isEmpty(dataset)) {
int index = -1;
for (E e: dataset) {
++index;
writer.write(worksheet, e, index);
}
}
if (styles != null) {
styles.clear();
styles = null;
}
return this;
}
/** .
* @param path
* @return
*/
public File write(String path) {
if (workbook == null)
throw new NullPointerException("No workbook to write");
try (FileOutputStream out = new FileOutputStream(path);) {
workbook.write(out);
return new File(path);
} catch (Exception e) {
throw applicationException(e);
}
}
}

@ -1,51 +1,43 @@
package cokr.xit.base.file.web; package cokr.xit.base.file.web;
import java.io.InputStream;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.view.AbstractView; import org.springframework.web.servlet.view.AbstractView;
import cokr.xit.foundation.Assert; import cokr.xit.base.file.xls.XLS;
/** .
* .
* 릿 . 릿
* https://jxls.sourceforge.net
* https://ddoriya.tistory.com/entry/JXLS-POI-JAVA%EC%97%90%EC%84%9C-Excel-%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94-%EA%B5%AC%ED%98%84-%EB%B0%A9%EB%B2%95-%EB%B0%8F-%EC%A2%85%EB%A5%98-%EB%B9%84%EA%B5%90
* 'xlsView' Bean
* (*Controller.java)
* ModelAndView 'xlsView'
* ModelAndView
* ('xls')
* DatasetControl (JSP / *.js)
*
* download()
*
* @author mjkhan
*/
public class XLSView extends AbstractView { public class XLSView extends AbstractView {
@Override @Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest hreq, HttpServletResponse hresp) throws Exception { protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest hreq, HttpServletResponse hresp) throws Exception {
try (InputStream input = getInputStream(model)) { XLS xls = (XLS)model.get("xls");
String filename = getFilename(model);
Context ctx = new Context();
model.forEach(ctx::putVar);
String charset = "UTF-8"; String charset = "UTF-8";
String filename = xls.getFilename();
hresp.setCharacterEncoding(charset); hresp.setCharacterEncoding(charset);
hresp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); hresp.setContentType(XLS.MIME_TYPE);
hresp.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(filename, charset) +"\""); hresp.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(filename, charset) +"\"");
JxlsHelper.getInstance().processTemplate(input, hresp.getOutputStream(), ctx); xls.write(hresp.getOutputStream());
}
}
private InputStream getInputStream(Map<String, Object> model) throws Exception {
String path = (String)model.remove("template");
if (Assert.isEmpty(path))
throw new RuntimeException("'template' not found");
return new ClassPathResource(path).getInputStream();
}
private String getFilename(Map<String, Object> model) {
return Assert.ifEmpty(
(String)model.remove("filename"),
() -> new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".xlsx"
);
} }
} }

@ -0,0 +1,68 @@
package cokr.xit.base.file.xls;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
public class JXLS extends XLS {
private Context ctx;
private Map<String, Object> data;
@Override
public JXLS setTemplate(String template) {
super.setTemplate(template);
return this;
}
@Override
public JXLS setFilename(String filename) {
super.setFilename(filename);
return this;
}
/** .
* @return
*/
public Map<String, Object> getData() {
return data != null ? data : Collections.emptyMap();
}
/** .
* @param map
* @return XLS
*/
public JXLS setData(Map<String, Object> map) {
data = map;
return this;
}
/** .
* @param key
* @param obj
* @return XLS
*/
public JXLS setData(String key, Object obj) {
if (data == null) {
data = new LinkedHashMap<>();
}
data.put(key, obj);
return this;
}
@Override
public void write(OutputStream out) {
ctx = new Context();
getData().forEach(ctx::putVar);
try (InputStream input = loadTemplate();) {
JxlsHelper.getInstance().processTemplate(input, out, ctx);
} catch (Exception e) {
throw runtimeException(e);
}
}
}

@ -0,0 +1,67 @@
package cokr.xit.base.file.xls;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.io.ClassPathResource;
import cokr.xit.foundation.AbstractComponent;
/**
* @author mjkhan
*/
public abstract class XLS extends AbstractComponent {
/**엑셀 파일(*.xlsx)의 mime type */
public static final String MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
private String
template,
filename;
/**릿 .
* @return 릿
*/
public String getTemplate() {
return template;
}
protected InputStream loadTemplate() throws Exception {
if (isEmpty(template))
return null;
return new ClassPathResource(template).getInputStream();
}
/**릿 .
* @param template 릿
* @return XLS
*/
public XLS setTemplate(String template) {
this.template = template;
return this;
}
/** .
* 'yyyyMMdd-HHmmss.xlsx'
* @return
*/
public String getFilename() {
return ifEmpty(filename, () -> new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".xlsx");
}
/** .
* 'yyyyMMdd-HHmmss.xlsx'
* @param filename
* @return XLS
*/
public XLS setFilename(String filename) {
this.filename = filename;
return this;
}
/** out .
* @param out OutputStream
*/
public abstract void write(OutputStream out);
}

@ -0,0 +1,728 @@
package cokr.xit.base.file.xls;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.function.Consumer;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** .
* XLSWriter 릿 .
* <pre><code> XLSWriter xlsx = new XLSWriter().setTemplate("...");</code></pre>
* XLSWriter .
* <pre><code> XLSWriter xlsx = new XLSWriter()
* .setTemplate("...")
* .setFilename("...");</code></pre>
* XLSWriter .
* <pre><code> xlsx.worksheet(0) //워크시트 설정
* .row(0) //첫번째 행
* .col(0); //첫번째 열의 셀을 작업셀로 설정</code></pre>
* .
* <pre><code> List&lt;DataObject> dataset = ...;</code></pre>
* XLSWriter .
* <pre><code> xlsx.values(dataset);</code></pre>
* dataset .
* dataset .
* <pre><code> xlsx.values(dataset, "RCPT_ID", "RCPT_DT", "PAYER_NM", "RCPT_AMT");</code></pre>
* dataset {@link KeyStyle} .
* <pre><code> CellStyle
* datetime = xlsx.yyyy_mm_dd_hh_mm_ss(),
* numeric = xlsx.n_nn0();
* xlsx.values(dataset, "RCPT_ID", xlsx.keyStyle("RCPT_DT", datetime), "PAYER_NM", xlsx.keyStyle("RCPT_AMT", numeric));</code></pre>
* @author mjkhan
*/
public class XLSWriter extends XLS {
private int rowAccessWindowSize = 128;
private SXSSFWorkbook workbook;
private SXSSFSheet worksheet;
private SXSSFRow row;
private SXSSFCell cell;
@Override
public XLSWriter setTemplate(String template) {
super.setTemplate(template);
return this;
}
@Override
public XLSWriter setFilename(String filename) {
super.setFilename(filename);
return this;
}
@Override
public void write(OutputStream out) {
try {
workbook.write(out);
workbook.dispose();
} catch (Exception e) {
throw runtimeException(e);
} finally {
clear();
}
}
private SXSSFWorkbook getWorkbook() {
if (workbook != null)
return workbook;
try {
InputStream template = loadTemplate();
if (template != null) {
XSSFWorkbook xssf = new XSSFWorkbook(template);
workbook = new SXSSFWorkbook(xssf, rowAccessWindowSize);
} else {
workbook = new SXSSFWorkbook(rowAccessWindowSize);
}
workbook.setCompressTempFiles(true);
return workbook;
} catch (Exception e) {
throw runtimeException(e);
}
}
/** .
* .
* @param index (0 )
* @return
*/
public XLSWriter worksheet(int index) {
try {
worksheet = getWorkbook().getSheetAt(index);
} catch (Exception e) {
worksheet = getWorkbook().createSheet();
}
worksheet.setRandomAccessWindowSize(rowAccessWindowSize);
return this;
}
/** .
* .
* @param name
* @return
*/
public XLSWriter worksheet(String name) {
try {
SXSSFWorkbook wb = getWorkbook();
worksheet = ifEmpty(wb.getSheet(name), () -> wb.createSheet(name));
worksheet.setRandomAccessWindowSize(rowAccessWindowSize);
return this;
} catch (Exception e) {
throw runtimeException(e);
}
}
/** (row) .
* .
* @param index (0 )
* @return XLSWriter
*/
public XLSWriter row(int index) {
row = ifEmpty(worksheet.getRow(index), () -> worksheet.createRow(index));
return this;
}
/** (column) .
* .
* @param index (0 )
* @return XLSWriter
*/
public XLSWriter col(int index) {
cell = ifEmpty(row.getCell(index), () -> row.createCell(index));
return this;
}
/** .
* @param row
* @param col
* @return XLSWriter
*/
public XLSWriter cell(int row, int col) {
return row(row).col(col);
}
/** .
* @param val
* @param style (CellStyle, Styler, KeyStyle)
* @return XLSWriter
*/
public XLSWriter value(Object val, Object style) {
if (isEmpty(val))
return this;
if (val instanceof String) {
cell.setCellValue((String)val);
} else if (val instanceof Number) {
Number number = (Number)val;
cell.setCellValue(number.doubleValue());
} else if (val instanceof Date) {
cell.setCellValue((Date)val);
} else if (val instanceof Boolean) {
Boolean b = (Boolean)val;
cell.setCellValue(b.booleanValue());
} else
throw new IllegalArgumentException(val.getClass().getName() + ": " + val);
setCellStyle(style);
return this;
}
/** .
* @param val
* @return XLSWriter
*/
public XLSWriter value(Object val) {
return value(val, null);
}
/** .<br />
* .<br />
* .
* <pre><code> XLSWriter xlsx = new XLSWriter()
* .setTemplate("...") // 템플릿 사용 시 지정
* .setFilename("...") // 다운로드 시 파일이름 지정
* .worksheet(0) // 워크시트 지정
* .cell(0, 0) // 작업셀 지정
* .rowValues(List.of("하나", 10000, new Date()));</code></pre>
* , .
* <pre><code> CellStyle numeric = xlsx.n_nn0(); //{@link #cellStyle(Styler)} 참고
* CellStyle datetime = xlsx.yyyy_mm_dd_hh_mm_ss();
* ...
* xlsx.rowValues(List.of("하나", 10000, numeric, new Date(), datetime));</code></pre>
* @param vals ( )
* @return XLSWriter
*/
public XLSWriter rowValues(Iterable<?> vals) {
if (!isEmpty(vals)) {
int start = cell.getColumnIndex(),
x = start;
for (Object val: vals) {
if (val instanceof Styler) {
setCellStyle(val);
} else if (val instanceof CellStyle) {
setCellStyle(val);
} else if (val instanceof KeyStyle) {
setCellStyle(val);
} else {
col(x).value(val);
++x;
}
}
col(start);
}
return this;
}
private void setCellStyle(Object obj) {
Styler styler = null;
CellStyle style = null;
if (obj instanceof CellStyle) {
style = (CellStyle)obj;
} else if (obj instanceof Styler) {
styler = (Styler)obj;
} else if (obj instanceof KeyStyle) {
KeyStyle keyStyle = (KeyStyle)obj;
styler = keyStyle.styler;
style = keyStyle.style;
}
if (styler != null) {
style = cellStyle(styler);
if (styler.width != null) {
if (styler.width < 256)
worksheet.setColumnWidth(cell.getColumnIndex(), styler.width * 256);
else
worksheet.autoSizeColumn(cell.getColumnIndex());
}
if (styler.height != null)
row.setHeight(styler.height);
}
if (style != null)
cell.setCellStyle(style);
}
private Iterable<?> vals(Map<?, ?> map, Object[] keysAndStyles) {
if (isEmpty(map))
return Collections.emptyList();
if (isEmpty(keysAndStyles))
return map.values();
ArrayList<Object> vals = new ArrayList<>();
for (Object obj: keysAndStyles) {
if (obj instanceof KeyStyle) {
KeyStyle keyStyle = (KeyStyle)obj;
Object val = map.get(keyStyle.key);
vals.add(val);
vals.add(keyStyle);
} else {
vals.add(map.get(obj));
}
}
return vals;
}
/** map .<br />
* .<br />
* {@link KeyStyle} .<br />
* map .
* <pre><code> DataObject rec = new DataObject().set("NO", 1).set("PAYER", "홍길동").set("RCPT_AMT", 10000).set("RCPT_DT", new Date());
* XLSWriter xlsx = new XLSWriter()
* .setTemplate("...") // 템플릿 사용 시 지정
* .setFilename("...") // 다운로드 시 파일이름 지정
* .worksheet(0) // 워크시트 지정
* .cell(0, 0) // 작업셀 지정
* .rowValues(rec);</code></pre>
* .
* <pre><code> xlsx.rowValues(rec, "PAYER", "RCPT_AMT", "RCPT_DT");</code></pre>
* RCPT_AMT, RCPT_DT .
* <pre><code> CellStyle numeric = xlsx.n_nn0(); //{@link #cellStyle(Styler)} 참고
* CellStyle datetime = xlsx.yyyy_mm_dd_hh_mm_ss();
* ...
* xlsx.rowValues(rec, "PAYER", xlsx.keyStyle("RCPT_AMT", numeric), xlsx.keyStyle("RCPT_DT", datetime));</code></pre>
* @param map
* @param keysAndStyles , {@link KeyStyle }
* @return XLSWriter
*/
public XLSWriter rowValues(Map<?, ?> map, Object... keysAndStyles) {
return rowValues(vals(map, keysAndStyles));
}
/** .
* .<br />
* {@link KeyStyle} .<br />
* .
* <pre><code> List&lt;DataObject> dataset = ...;
* XLSWriter xlsx = new XLSWriter()
* .setTemplate("...") // 템플릿 사용 시 지정
* .setFilename("...") // 다운로드 시 파일이름 지정
* .worksheet(0) // 워크시트 지정
* .cell(0, 0) // 작업셀 지정
* .rowValues(dataset);</code></pre>
* .
* <pre><code> xlsx.rowValues(dataset, "PAYER", "RCPT_AMT", "RCPT_DT");</code></pre>
* RCPT_AMT, RCPT_DT .
* <pre><code> CellStyle numeric = xlsx.n_nn0(); //{@link #cellStyle(Styler)} 참고
* CellStyle datetime = xlsx.yyyy_mm_dd_hh_mm_ss();
* ...
* xlsx.rowValues(dataset, "PAYER", xlsx.keyStyle("RCPT_AMT", numeric), xlsx.keyStyle("RCPT_DT", datetime));</code></pre>
* @param dataset
* @param keysAndStyles , {@link KeyStyle }
* @return XLSWriter
*/
public XLSWriter values(Iterable<? extends Map<?, ?>> dataset, Object... keysAndStyles) {
if (!isEmpty(dataset)) {
int c = cell.getColumnIndex(),
r = cell.getRowIndex();
for (Map<?, ?> rec: dataset) {
cell(r, c);
rowValues(rec, keysAndStyles);
++r;
}
}
return this;
}
public XLSWriter styles(Styler... stylers) {
if (!isEmpty(stylers)) {
int start = cell.getColumnIndex(),
x = start;
for (Styler styler: stylers) {
col(x);
setCellStyle(styler);
++x;
}
col(start);
}
return this;
}
/** .
* @param styler
* @return
*/
public CellStyle cellStyle(Styler styler) {
CellStyle cellStyle = workbook.createCellStyle();
styler.set(cellStyle);
if (styler.dataFormat != null) {
cellStyle.setDataFormat(workbook.createDataFormat().getFormat(styler.dataFormat));
}
return cellStyle;
}
/** KeyStyle .
* @param key
* @param style
* @return KeyStyle
*/
public KeyStyle keyStyle(Object key, CellStyle style) {
return new KeyStyle(key, style);
}
/**style KeyStyle .
* @param key
* @param style
* @return
*/
public KeyStyle keyStyle(Object key, Styler style) {
return keyStyle(key, cellStyle(style));
}
/** XLSWriter .
* @return XLSWriter
*/
public XLSWriter clear() {
cell = null;
row = null;
worksheet = null;
workbook = null;
rowAccessWindowSize = 128;
return this;
}
/** ( , ) .
* @return ( , )
*/
public CellStyle n_nn0() {
return cellStyle(new Styler().alignment(HorizontalAlignment.RIGHT).dataFormat("#,###"));
}
/** ( , , 2 ) .
* @return ( , , 2 )
*/
public CellStyle n_nn0_2() {
return cellStyle(new Styler().dataFormat("#,###.00").merge(Styler.RIGHT));
}
/** (yyyy-MM-dd HH:mm:ss) .
* @return (yyyy-MM-dd HH:mm:ss)
*/
public CellStyle yyyy_mm_dd_hh_mm_ss() {
return cellStyle(new Styler().dataFormat("yyyy-MM-dd HH:mm:ss").merge(Styler.CENTER));
}
/** (yyyy-MM-dd) .
* @return (yyyy-MM-dd)
*/
public CellStyle yyyy_mm_dd() {
return cellStyle(new Styler().dataFormat("yyyy-MM-dd").merge(Styler.CENTER));
}
/** . {@link #set(CellStyle) CellStyle } .
* @author mjkhan
*/
public static class Styler {
/** 빈 스타일 */
public static final Styler NONE = new Styler().seal();
/** 좌측 정렬 */
public static final Styler LEFT = new Styler().alignment(HorizontalAlignment.LEFT).seal();
/** 가운데 정렬 */
public static final Styler CENTER = new Styler().alignment(HorizontalAlignment.CENTER).seal();
/** 우측 정렬 */
public static final Styler RIGHT = new Styler().alignment(HorizontalAlignment.RIGHT).seal();
private boolean sealed;
private Integer width;
private Short height;
private HorizontalAlignment horizontalAlignment;
private VerticalAlignment verticalAlignment;
private Border
borderTop,
borderRight,
borderBottom,
borderLeft;
private Short foregroundColor;
private Font font;
private String dataFormat;
/** .
* @param chars .
* @return Styler
*/
public Styler width(int chars) {
this.width = chars;
return this;
}
/** .
* @param height
* @return Styler
*/
public Styler height(short height) {
this.height = height;
return this;
}
/** .
* @param alignment
* @return Styler
*/
public Styler alignment(HorizontalAlignment alignment) {
ensureNotSealed();
horizontalAlignment = alignment;
return this;
}
/** .
* @param alignment
* @return Styler
*/
public Styler alignment(VerticalAlignment alignment) {
ensureNotSealed();
verticalAlignment = alignment;
return this;
}
/** .
* @param border
* @return Styler
*/
public Styler borderTop(Border border) {
ensureNotSealed();
borderTop = border;
return this;
}
/** .
* @param border
* @return Styler
*/
public Styler borderRight(Border border) {
ensureNotSealed();
borderRight = border;
return this;
}
/** .
* @param border
* @return Styler
*/
public Styler borderBottom(Border border) {
ensureNotSealed();
borderBottom = border;
return this;
}
/** .
* @param border
* @return Styler
*/
public Styler borderLeft(Border border) {
ensureNotSealed();
borderLeft = border;
return this;
}
/** .
* @param color
* @return Styler
*/
public Styler foregroundColor(short color) {
ensureNotSealed();
foregroundColor = color;
return this;
}
/** .
* @param font
* @return Styler
*/
public Styler font(Font font) {
ensureNotSealed();
this.font = font;
return this;
}
/** .
* @param dataFormat
* @return Styler
*/
public Styler dataFormat(String dataFormat) {
ensureNotSealed();
this.dataFormat = dataFormat;
return this;
}
/** .
* @param style
*/
public void set(CellStyle style) {
if (style == null) return;
if (horizontalAlignment != null)
style.setAlignment(horizontalAlignment);
if (verticalAlignment != null)
style.setVerticalAlignment(verticalAlignment);
if (borderTop != null) {
if (borderTop.style != null)
style.setBorderTop(borderTop.style);
if (borderTop.color != null)
style.setTopBorderColor(borderTop.color);
}
if (borderRight != null) {
if (borderRight.style != null)
style.setBorderRight(borderRight.style);
if (borderRight.color != null)
style.setRightBorderColor(borderRight.color);
}
if (borderBottom != null) {
if (borderBottom.style != null)
style.setBorderBottom(borderBottom.style);
if (borderBottom.color != null)
style.setBottomBorderColor(borderBottom.color);
}
if (borderLeft != null) {
if (borderLeft.style != null)
style.setBorderLeft(borderLeft.style);
if (borderLeft.color != null)
style.setLeftBorderColor(borderLeft.color);
}
if (foregroundColor != null) {
style.setFillForegroundColor(foregroundColor);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}
if (font != null)
style.setFont(font);
}
public Styler configure(Consumer<Styler> configurer) {
ensureNotSealed();
if (configurer != null)
configurer.accept(this);
return this;
}
public Styler merge(Styler other) {
Styler copy = new Styler();
copy.width = this.width;
copy.height = this.height;
copy.horizontalAlignment = this.horizontalAlignment;
copy.verticalAlignment = this.verticalAlignment;
copy.borderTop = this.borderTop;
copy.borderRight = this.borderRight;
copy.borderBottom = this.borderBottom;
copy.borderLeft = this.borderLeft;
copy.foregroundColor = this.foregroundColor;
copy.font = this.font;
copy.dataFormat = this.dataFormat;
if (other.width != null)
copy.width = other.width;
if (other.height != null)
copy.height = other.height;
if (other.horizontalAlignment != null)
copy.horizontalAlignment = other.horizontalAlignment;
if (other.verticalAlignment != null)
copy.verticalAlignment = other.verticalAlignment;
if (other.borderTop != null)
copy.borderTop = other.borderTop;
if (other.borderRight != null)
copy.borderRight = other.borderRight;
if (other.borderBottom != null)
copy.borderBottom = other.borderBottom;
if (other.borderLeft != null)
copy.borderLeft = other.borderLeft;
if (other.foregroundColor != null)
copy.foregroundColor = other.foregroundColor;
if (other.font != null)
copy.font = other.font;
if (other.dataFormat != null)
copy.dataFormat = other.dataFormat;
return copy;
}
private Styler seal() {
sealed = true;
return this;
}
private void ensureNotSealed() {
if (sealed)
throw new RuntimeException("The Style is sealed and unmodifieable");
}
}
/**
* @author mjkhan
*/
public static class Border {
private BorderStyle style;
private Short color;
/** .
* @param style
* @return
*/
public Border style(BorderStyle style) {
this.style = style;
return this;
}
/** .
* @param color
* @return
*/
public Border color(short color) {
this.color = color;
return this;
}
}
/**
* @author mjkhan
*/
public static class KeyStyle {
private Object key;
private CellStyle style;
private Styler styler;
/** KeyStyle .
* @param key
* @param style
*/
KeyStyle(Object key, CellStyle style) {
this.key = notEmpty(key, "key");
this.style = style;
}
/** KeyStyle .
* @param key
* @param styler
*/
KeyStyle(Object key, Styler styler) {
this.key = notEmpty(key, "key");
this.styler = styler;
}
}
}
Loading…
Cancel
Save