All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gomcarter.frameworks.xmlexcel.Appender Maven / Gradle / Ivy

The newest version!
package com.gomcarter.frameworks.xmlexcel;

import com.gomcarter.frameworks.xmlexcel.config.Format;
import com.gomcarter.frameworks.xmlexcel.config.Header;
import com.gomcarter.frameworks.xmlexcel.config.Style;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author gomcarter on 2016年4月6日 13:20:55
 */
public class Appender {

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    public enum DefaultStyle {
        /**
         * DEFAULT
         */
        DEFAULT(Style.of("Default")),
        /**
         * TABLE
         */
        TABLE(Style.of("t01")),
        /**
         * HEADER
         */
        HEADER(Style.of("s01", null, true, "#00B050", Format.defaults)),
        /**
         * TEXT
         */
        TEXT(Style.of("s02", null, false, null, Format.defaults)),
        /**
         * FLOAT
         */
        FLOAT(Style.of("s03", null, false, null, Format.number)),
        /**
         * INTEGER
         */
        INTEGER(Style.of("s04", null, false, null, Format.integer));

        public Style style;

        DefaultStyle(Style style) {
            this.style = style;
        }

        public static Collection",
                        s.getKey(),
                        //make the default color black if configured color is null
                        Optional.ofNullable(s.getColor()).orElse("#000000"),
                        s.isBold() ? "ss:Bold=\"1\"" : "",
                        s.getInterior() == null ? "" : (""),
                        s.getFormat() == null ? "" : s.getFormat().get()))
                .reduce((a, b) -> a + b)
                .orElse("");

        return String.format("%s", g).getBytes(DEFAULT_CHARSET);
    }

    public static byte[] sheet(String sheetName) {
        //TODO: consider the column width to be configurable
//        return ("\n" +
//                "  \n" +
//                "   \n" +
//                "   \n" +
//                "   \n" +
//                "   \n" +
//                "   ").getBytes(DEFAULT_CHARSET);

        return ("" +
                "
").getBytes(DEFAULT_CHARSET); } /** * @param sheetName : 外部控制sheetName不重复 * @return byte */ public static byte[] nextSheet(String sheetName) { return ("
" + "" + "").getBytes(DEFAULT_CHARSET); } /** * @param headers headers * @return byte */ public static byte[] header(List
headers) { StringBuilder define = new StringBuilder(); // StringBuffer row = new StringBuffer(" "); StringBuilder row = new StringBuilder(" "); for (int i = 0; i < headers.size(); ++i) { Header header = headers.get(i); /*设置列宽*/ Integer width = header.getWidth(); if (null != width && 0 < width) { define.append(""); } /*添加表头*/ row.append("") .append(header.getName()) .append(""); } row.append(""); return define.append(row).toString().getBytes(DEFAULT_CHARSET); } public static byte[] row(List
headers, Map element) { return rows(headers, Collections.singletonList(element)); } /** * @param headers headers * @param elements List<map<headerkey, data>> * @return byte */ public static byte[] rows(List
headers, Collection elements) { if (elements == null || elements.size() <= 0) { return new byte[0]; } List
headerList = Optional.ofNullable(headers).orElse(parseHeaders(elements)); if (headers.stream().anyMatch(Header::getAutoMerge)) { //需要自动合并 return merge(headerList, elements); } else { //不需要自动合并 return directly(headerList, elements); } } private static class Pair { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } } private static byte[] merge(List
headerList, Collection elements) { Map toBeMergedCache = new HashMap<>(); List> rows = elements .stream() .map(row -> new HashMap() {{ for (Header h : headerList) { Object value = null; String key = h.getName(); Function formatter = h.getDataFormatter(); if (formatter != null) { value = formatter.apply(row); } Pair current = new Pair<>(0, value); put(key, current); if (h.getAutoMerge()) { //如果是需要merge的列; Pair prev = toBeMergedCache.get(key); if (prev == null) { toBeMergedCache.put(key, current); } else { //看当前和之前的值是否相等,相等则标记合并+1,不相等换新的 if (Objects.equals(prev.value, value)) { //key 相当于向下合并多少单元格 prev.key++; //key 等于 -1 相当于表示改cell不显示 current.key = -1; } else { toBeMergedCache.put(key, current); } } } } }}) .collect(Collectors.toList()); return body(headerList, rows); } private static byte[] body(List
headerList, List> elements) { return elements.stream() .map(row -> { StringBuilder sb = new StringBuilder(""); for (int i = 1; i <= headerList.size(); ++i) { Header h = headerList.get(i - 1); Pair pair = row.get(h.getName()); Object value = pair.value; int key = pair.key; if (key < 0) { //小于0表示被合并了,这一个单元格不写数据 continue; } else if (key > 0) { //大于零表示第一个开始合并,需要标明往下合并多少单元格 sb.append("") .append(v == null ? "" : v.toString()) .append(""); } return sb.append("\n").toString(); }) .reduce((a, b) -> a + b) .orElse("") .getBytes(DEFAULT_CHARSET); } private static byte[] directly(List
headerList, Collection elements) { List> rows = elements.stream() .map(row -> new HashMap() {{ for (Header h : headerList) { Object value = null; Function formatter = h.getDataFormatter(); if (formatter != null) { value = formatter.apply(row); } put(h.getName(), new Pair<>(0, value)); } }}) .collect(Collectors.toList()); return body(headerList, rows); } public static byte[] end() { return "
".getBytes(DEFAULT_CHARSET); } public static List
parseHeaders(Collection rows) { return rows.stream() .limit(1) .map(s -> { if (Arrays.stream(s.getClass().getGenericInterfaces()) .anyMatch(m -> ((ParameterizedTypeImpl) m).getRawType() == Map.class)) { return new ArrayList
() {{ ((Map) s).forEach((key, value) -> add(Header.of(key + ""))); }}; } else { return new ArrayList
() {{ Arrays.stream(s.getClass().getDeclaredFields()) .forEach(s -> add(Header.of(s.getName()))); }}; } }) .findAny() .orElse(null); } public static Object format(Object data) { if (data == null) { return null; } else if (data instanceof Date) { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(data); } else if (data instanceof String) { return ((String) data).replaceAll("<", "<") .replaceAll(">", ">"); } return data; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy