LuckySheet工具类
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;
import java.awt.Color;
import java.io.*;
import java.util.*;
import java.util.List;
public class ExportExcel {
public static void exportLuckySheetXlsxByPOI(String title, String newFileDir, String newFileName, String excelData) {
excelData = excelData.replace("
", "\\r\\n");
JSONArray jsonArray = (JSONArray) JSONObject.parse(excelData);
XSSFWorkbook excel = new XSSFWorkbook();
for (int sheetIndex = 0; sheetIndex < jsonArray.size(); sheetIndex++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(sheetIndex);
JSONArray celldataObjectList = jsonObject.getJSONArray("celldata");
JSONArray rowObjectList = jsonObject.getJSONArray("visibledatarow");
JSONArray colObjectList = jsonObject.getJSONArray("visibledatacolumn");
JSONArray dataObjectList = jsonObject.getJSONArray("data");
JSONObject mergeObject = jsonObject.getJSONObject("config").getJSONObject("merge");
JSONObject columnlenObject = jsonObject.getJSONObject("config").getJSONObject("columnlen");
JSONObject colhiddenObject = jsonObject.getJSONObject("config").getJSONObject("colhidden");
JSONObject rowlenObject = jsonObject.getJSONObject("config").getJSONObject("rowlen");
JSONArray borderInfoObjectList = jsonObject.getJSONObject("config").getJSONArray("borderInfo");
JSONObject imagesObject = jsonObject.getJSONObject("images");
String imgSrc="";
if(imagesObject!=null&&imagesObject.size()>0){
for(String object:imagesObject.keySet()){
if(((JSONObject)imagesObject.get(object)).containsKey("src")){
imgSrc=((JSONObject)imagesObject.get(object)).getString("src");
break;
}
}
}
XSSFSheet sheet = excel.createSheet(jsonObject.getString("name"));
try {
String path=Thread.currentThread().getContextClassLoader().getResource("").getPath();
InputStream is = new FileInputStream(path.substring(0,path.indexOf("图片路径");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = excel.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
is.close();
CreationHelper helper = excel.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(0);
anchor.setCol2(6);
anchor.setRow2(3);
Picture pict = drawing.createPicture(anchor, pictureIdx);
} catch (Exception e) {
e.printStackTrace();
}
Header header= sheet.getHeader();
header.setLeft("&L&G");
HSSFHeader.fontSize((short) 16);
System.out.println("excel Sheets数量-------" + excel.getNumberOfSheets() + jsonObject.getString("name"));
List<JSONObject> cells_json = (List<JSONObject>) jsonObject.get("celldata");
Map<Integer, List<JSONObject>> cellMap = cellGroup(cells_json);
System.out.println("设置单元格值BEGIN");
long beginTime=System.currentTimeMillis();
for (Integer r : cellMap.keySet()) {
Row row = sheet.createRow(r);
sheet.setForceFormulaRecalculation(true);
for (JSONObject col : cellMap.get(r)) {
createCell(excel, sheet, row, col);
}
}
long beginTime2=System.currentTimeMillis();
System.out.println("设置单元格值END耗时:"+(beginTime2-beginTime));
System.out.println("设置行列宽高BEGIN");
if (rowlenObject != null) {
for (String k : rowlenObject.keySet()) {
Integer _i = getStrToInt(k);
Integer _v = getStrToInt(rowlenObject.get(k).toString());
if (_i != null && _v != null) {
Row row = sheet.getRow(_i);
if (row != null) {
row.setHeightInPoints(_v.shortValue());
}
}
}
}
if (columnlenObject != null) {
for (String k : columnlenObject.keySet()) {
Integer _i = getStrToInt(k);
Integer _v = getStrToInt(columnlenObject.get(k).toString());
if (_i != null && _v != null) {
sheet.setColumnWidth(_i, _v.shortValue() * 42);
}
}
}
if (colhiddenObject != null) {
for (String k : colhiddenObject.keySet()) {
Integer _i = getStrToInt(k);
Integer _v = getStrToInt(colhiddenObject.get(k).toString());
if (_i != null && _v != null) {
sheet.setColumnHidden(_i,true);
}
}
}
long beginTime3=System.currentTimeMillis();
System.out.println("设置行列宽高END耗时:"+(beginTime3-beginTime2));
System.out.println("设置边框BEGIN");
setBorder(borderInfoObjectList, excel, sheet);
long beginTime4=System.currentTimeMillis();
System.out.println("设置边框END"+(beginTime4-beginTime3));
}
File dir = new File(newFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
String paths = newFileDir + newFileName;
OutputStream out = null;
File f = new File(paths);
if (!f.exists()) {
System.out.println("有了");
}
try {
out = new FileOutputStream(paths);
excel.write(out);
out.close();
} catch (IOException e) {
System.out.println("输出语句2");
}
System.out.println("输出语句0");
}
private static void setMergeAndColorByObject(JSONObject jsonObjectValue, XSSFSheet sheet, XSSFCellStyle style) {
JSONObject mergeObject = (JSONObject) jsonObjectValue.get("mc");
if (mergeObject != null) {
int r = (int) (mergeObject.get("r"));
int c = (int) (mergeObject.get("c"));
if ((mergeObject.get("rs") != null && (mergeObject.get("cs") != null))) {
int rs = (int) (mergeObject.get("rs"));
int cs = (int) (mergeObject.get("cs"));
CellRangeAddress region = new CellRangeAddress(r, r + rs - 1, (short) (c), (short) (c + cs - 1));
sheet.addMergedRegion(region);
}
}
if (jsonObjectValue.getString("bg") != null && jsonObjectValue.getString("bg").indexOf("rgb") != 0) {
int bg = Integer.parseInt(jsonObjectValue.getString("bg").replace("#", ""), 16);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(new XSSFColor(new Color(bg)));
}
}
private static void setBorder(JSONArray borderInfoObjectList, XSSFWorkbook workbook, XSSFSheet sheet) {
Map<Integer, BorderStyle> bordMap = new HashMap<>();
bordMap.put(1, BorderStyle.THIN);
bordMap.put(2, BorderStyle.HAIR);
bordMap.put(3, BorderStyle.DOTTED);
bordMap.put(4, BorderStyle.DASHED);
bordMap.put(5, BorderStyle.DASH_DOT);
bordMap.put(6, BorderStyle.DASH_DOT_DOT);
bordMap.put(7, BorderStyle.DOUBLE);
bordMap.put(8, BorderStyle.MEDIUM);
bordMap.put(9, BorderStyle.MEDIUM_DASHED);
bordMap.put(10, BorderStyle.MEDIUM_DASH_DOT);
bordMap.put(12, BorderStyle.SLANTED_DASH_DOT);
bordMap.put(13, BorderStyle.THICK);
for (int i = 0; i < borderInfoObjectList.size(); i++) {
try {
JSONObject borderInfoObject = (JSONObject) borderInfoObjectList.get(i);
JSONObject borderValueObject = borderInfoObject.getJSONObject("value");
JSONObject l = borderValueObject.getJSONObject("l");
JSONObject r = borderValueObject.getJSONObject("r");
JSONObject t = borderValueObject.getJSONObject("t");
JSONObject b = borderValueObject.getJSONObject("b");
int row = borderValueObject.getInteger("row_index");
int col = borderValueObject.getInteger("col_index");
if (l != null && l.containsKey("color") && l.getString("color").contains("rgb")
|| r != null && r.containsKey("color") && r.getString("color").contains("rgb")
|| t != null && t.containsKey("color") && t.getString("color").contains("rgb")
|| b != null && b.containsKey("color") && b.getString("color").contains("rgb")) {
continue;
}
XSSFCell cell = sheet.getRow(row).getCell(col);
if (l != null) {
cell.getCellStyle().setBorderLeft(bordMap.get(l.get("style")));
int bg = Integer.parseInt(l.getString("color").replace("#", ""), 16);
cell.getCellStyle().setLeftBorderColor(new XSSFColor(new Color(bg)));
} else {
cell.getCellStyle().setBorderLeft(BorderStyle.NONE);
}
if (r != null) {
cell.getCellStyle().setBorderRight(bordMap.get(r.get("style")));
int bg = Integer.parseInt(r.getString("color").replace("#", ""), 16);
cell.getCellStyle().setRightBorderColor(new XSSFColor(new Color(bg)));
} else {
cell.getCellStyle().setBorderRight(BorderStyle.NONE);
}
if (t != null) {
cell.getCellStyle().setBorderTop(bordMap.get(t.get("style")));
int bg = Integer.parseInt(t.getString("color").replace("#", ""), 16);
cell.getCellStyle().setTopBorderColor(new XSSFColor(new Color(bg)));
} else {
cell.getCellStyle().setBorderTop(BorderStyle.NONE);
}
if (b != null) {
cell.getCellStyle().setBorderBottom(bordMap.get(b.get("style")));
int bg = Integer.parseInt(t.getString("color").replace("#", ""), 16);
cell.getCellStyle().setTopBorderColor(new XSSFColor(new Color(bg)));
} else {
cell.getCellStyle().setBorderBottom(BorderStyle.NONE);
}
} catch (Exception e) {
}
}
}
public static boolean isNumeric(String str) {
String regex = "\\d+(\\.\\d+)?";
return str.matches(regex);
}
private static Integer getStrToInt(Object str) {
try {
if (str != null) {
return Integer.parseInt(str.toString());
}
return null;
} catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
}
public static Map<Integer, List<JSONObject>> cellGroup(List<JSONObject> cells) {
Map<Integer, List<JSONObject>> cellMap = new HashMap<>(100);
for (JSONObject dbObject : cells) {
if (dbObject.containsKey("r")) {
Integer r = getStrToInt(dbObject.get("r"));
if (r != null) {
if (cellMap.containsKey(r)) {
cellMap.get(r).add(dbObject);
} else {
List<JSONObject> list = new ArrayList<>(10);
list.add(dbObject);
cellMap.put(r, list);
}
}
}
}
return cellMap;
}
private static void createCell(XSSFWorkbook wb, XSSFSheet sheet, Row row, JSONObject dbObject) {
if (dbObject.containsKey("c")) {
Integer c = getStrToInt(dbObject.get("c"));
if (c != null) {
Cell cell = row.createCell(c);
if (dbObject.containsKey("v")) {
Object obj = dbObject.get("v");
if (obj == null) {
return;
}
if (obj instanceof String) {
if (((String) obj).length() > 0) {
cell.setCellValue(obj.toString());
}
return;
}
JSONObject v_json = (JSONObject) obj;
XSSFCellStyle style = wb.createCellStyle();
cell.setCellStyle(style);
if (v_json.containsKey("mc")) {
JSONObject mc = v_json.getJSONObject("mc");
if (mc.containsKey("rs") && mc.containsKey("cs")) {
if (mc.containsKey("r") && mc.containsKey("c")) {
Integer _rs = getIntByDBObject(mc, "rs") - 1;
Integer _cs = getIntByDBObject(mc, "cs") - 1;
Integer _r = getIntByDBObject(mc, "r");
Integer _c = getIntByDBObject(mc, "c");
CellRangeAddress region = new CellRangeAddress(_r.shortValue(),
(_r.shortValue() + _rs.shortValue()), _c.shortValue(),
(_c.shortValue() + _cs.shortValue()));
sheet.addMergedRegion(region);
}
} else {
return;
}
}
setFormatByCt(wb, cell, style, v_json);
setCellStyleFont(wb, style, v_json,cell);
if (v_json.containsKey("bg")) {
String _v = getByDBObject(v_json, "bg");
if (_v != null) {
Short _color = ColorUtil.getColorByStr(_v);
if (_color != null) {
style.setFillForegroundColor(_color);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}
}
}
if (v_json.containsKey("vt")) {
Integer _v = getIntByDBObject(v_json, "vt");
if (_v != null && _v >= 0 && _v <= 2) {
style.setVerticalAlignment(ConstantUtil.getVerticalType(_v));
}
}
if (v_json.containsKey("ht")) {
Integer _v = getIntByDBObject(v_json, "ht");
if (_v != null && _v >= 0 && _v <= 2) {
style.setAlignment(ConstantUtil.getHorizontaltype(_v));
}
}
if (v_json.containsKey("tr")) {
Integer _v = getIntByDBObject(v_json, "tr");
if (_v != null) {
style.setRotation(ConstantUtil.getRotation(_v));
}
}
if (v_json.containsKey("tb")) {
Integer _v = getIntByDBObject(v_json, "tb");
if (_v != null) {
if (_v >= 0 && _v <= 1) {
style.setWrapText(false);
} else {
style.setWrapText(true);
}
}
}
if (v_json.containsKey("f")) {
String _v = getByDBObject(v_json, "f");
if (_v.length() > 0) {
try {
if (_v.startsWith("=")) {
cell.setCellFormula(_v.substring(1));
} else {
cell.setCellFormula(_v);
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
}
}
}
}
public static Integer getIntByDBObject(JSONObject b, String k) {
if (b.containsKey(k)) {
if (b.get(k) != null) {
try {
String _s = b.getString(k).replace("px", "");
Double _d = Double.parseDouble(_s);
return _d.intValue();
} catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
}
}
return null;
}
public static String getByDBObject(JSONObject b, String k) {
if (b.containsKey(k)) {
if (b.get(k) != null && b.get(k) instanceof String) {
return b.getString(k);
}
}
return null;
}
private static void setFormatByCt(Workbook wb, Cell cell, CellStyle style, JSONObject dbObject) {
if (!dbObject.containsKey("v") && dbObject.containsKey("ct")) {
JSONObject ct = dbObject.getJSONObject("ct");
if (ct.containsKey("s")) {
Object s = ct.get("s");
if (s instanceof List && ((List) s).size() > 0) {
StringBuilder _v=new StringBuilder();
for(int i=0;i<((List<?>) s).size();i++){
JSONObject _s1 = (JSONObject) ((List) s).get(i);
if (_s1.containsKey("v") && _s1.get("v") instanceof String) {
_v.append(_s1.getString("v"));
}
}
dbObject.put("v", _v);
style.setWrapText(true);
}
}
if (ct.containsKey("fa")) {
String fa = ct.getString("fa");
DataFormat format = wb.createDataFormat();
style.setDataFormat(format.getFormat(fa));
}
}
if (dbObject.containsKey("v")) {
Object obj = getObjectByDBObject(dbObject, "v");
if (obj instanceof Number) {
cell.setCellValue(Double.valueOf(obj.toString()));
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Calendar) {
cell.setCellValue((Calendar) obj);
} else if (obj instanceof RichTextString) {
cell.setCellValue((RichTextString) obj);
} else if (obj instanceof String) {
cell.setCellValue((String) obj);
} else {
cell.setCellValue(obj.toString());
}
}
if (dbObject.containsKey("ct")) {
JSONObject ct = dbObject.getJSONObject("ct");
if (ct.containsKey("fa") && ct.containsKey("t")) {
String fa = getByDBObject(ct, "fa");
String t = getByDBObject(ct, "t");
Integer _i = ConstantUtil.getNumberFormatMap(fa);
switch (t) {
case "s": {
if (_i >= 0) {
style.setDataFormat(_i.shortValue());
} else {
style.setDataFormat((short) 0);
}
break;
}
case "d": {
Date _d = null;
String v = getByDBObject(dbObject, "m");
if (v.length() == 0) {
v = getByDBObject(dbObject, "v");
}
if (v.length() > 0) {
if (v.indexOf("-") > -1) {
if (v.indexOf(":") > -1) {
_d = ConstantUtil.stringToDateTime(v);
} else {
_d = ConstantUtil.stringToDate(v);
}
} else {
_d = ConstantUtil.toDate(v);
}
}
if (_d != null) {
cell.setCellValue(_d);
DataFormat format = wb.createDataFormat();
style.setDataFormat(format.getFormat(fa));
} else {
if (_i >= 0) {
style.setDataFormat(_i.shortValue());
} else {
style.setDataFormat((short) 0);
}
}
break;
}
case "b": {
if (_i >= 0) {
style.setDataFormat(_i.shortValue());
} else {
DataFormat format = wb.createDataFormat();
style.setDataFormat(format.getFormat(fa));
}
break;
}
case "n": {
if (_i >= 0) {
style.setDataFormat(_i.shortValue());
} else {
DataFormat format = wb.createDataFormat();
style.setDataFormat(format.getFormat(fa));
}
break;
}
case "u":
case "g": {
if (_i >= 0) {
style.setDataFormat(_i.shortValue());
} else {
DataFormat format = wb.createDataFormat();
style.setDataFormat(format.getFormat(fa));
}
break;
}
case "e": {
if (_i >= 0) {
style.setDataFormat(_i.shortValue());
} else {
DataFormat format = wb.createDataFormat();
style.setDataFormat(format.getFormat(fa));
}
break;
}
}
}
}
}
public static Object getObjectByDBObject(JSONObject b, String k) {
if (b.containsKey(k)) {
if (b.get(k) != null) {
return b.get(k);
}
}
return "";
}
private static void setCellStyleFont(XSSFWorkbook wb, CellStyle style, JSONObject dbObject,Cell cell) {
XSSFFont font = wb.createFont();
if (dbObject.containsKey("ff")) {
if (dbObject.get("ff") instanceof Integer) {
Integer _v = getIntByDBObject(dbObject, "ff");
if (_v != null && ConstantUtil.ff_IntegerToName.containsKey(_v)) {
font.setFontName(ConstantUtil.ff_IntegerToName.get(_v));
}
} else if (dbObject.get("ff") instanceof String) {
font.setFontName(getByDBObject(dbObject, "ff"));
}
}
if (dbObject.containsKey("fc")) {
String _v = getByDBObject(dbObject, "fc");
if (_v != null) {
Short _color = ColorUtil.getColorByStr(_v);
if (_color != null) {
font.setColor(_color);
}
}
}
if (dbObject.containsKey("bl")) {
Integer _v = getIntByDBObject(dbObject, "bl");
if (_v != null) {
if (_v.equals(1)) {
font.setBold(true);
} else {
font.setBold(false);
}
}
}
if (dbObject.containsKey("it")) {
Integer _v = getIntByDBObject(dbObject, "it");
if (_v != null) {
if (_v.equals(1)) {
font.setItalic(true);
} else {
font.setItalic(false);
}
}
}
if (dbObject.containsKey("fs")) {
Integer _v = getStrToInt(getObjectByDBObject(dbObject, "fs"));
if (_v != null) {
font.setFontHeightInPoints(_v.shortValue());
}
}
if (dbObject.containsKey("cl")) {
Integer _v = getIntByDBObject(dbObject, "cl");
if (_v != null) {
if (_v.equals(1)) {
font.setStrikeout(true);
}
}
}
if (dbObject.containsKey("ul")) {
Integer _v = getIntByDBObject(dbObject, "ul");
if (_v != null) {
if (_v.equals(1)) {
font.setUnderline(Font.U_SINGLE);
} else {
font.setUnderline(Font.U_NONE);
}
}
}
style.setFont(font);
cell.setCellStyle(style);
}
}