工具类代码
/** * json工具类 */ public class JsonUtil { private static final Gson gson; private static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; static { // LocalDateTime的序列化 JsonSerializer<LocalDateTime> localDateTimeJsonSerializer = (localDateTime, type, jsonSerializationContext) -> { if (localDateTime == null) { return new JsonPrimitive(""); } return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern(TIME_FORMAT))); }; // LocalDateTime的反序列化 JsonDeserializer<LocalDateTime> localDateTimeJsonDeserializer = (jsonElement, type, jsonDeserializationContext) -> { String str = jsonElement.getAsJsonPrimitive().getAsString(); if (str == null || str.isEmpty()) { return null; } return LocalDateTime.parse(str, DateTimeFormatter.ofPattern(TIME_FORMAT)); }; gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss") .registerTypeAdapter(LocalDateTime.class, localDateTimeJsonSerializer) .registerTypeAdapter(LocalDateTime.class, localDateTimeJsonDeserializer) .create(); } /** * java对象转json字符串 * @param object * @return */ public static String toJson(Object object) { return gson.toJson(object); } /** * json字符串转换为T类型的对象 * @param text json字符串 * @param tClass T的class * @return T对象 */ public static <T> T fromJson(String text, Class<T> tClass) { return gson.fromJson(text, tClass); } /** * json字符串转Object * @param text json字符串 * @return Object */ public static Object parse(String text) { return gson.fromJson(text, Object.class); } }
package com.example.demo.util; import com.google.gson.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Set; public class HttpUtil { public static String post(String httpUrl, Object param) throws IOException { String paramStr = toUrlString(param); return post(httpUrl, param); } private static String post(String httpUrl, String param) throws IOException { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(2000); connection.setReadTimeout(10000); connection.setDoOutput(true); connection.setDoInput(true); String ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; connection.setRequestProperty("Content-Type", ContentType); os = connection.getOutputStream(); os.write(param.getBytes()); if (connection.getResponseCode() == 200) { is = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); StringBuilder sbf = new StringBuilder(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } finally { if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } public static String toUrlString(Object object) throws UnsupportedEncodingException { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); String json = gson.toJson(object); JsonElement jsonElement = JsonParser.parseString(json); JsonObject jsonObject = jsonElement.getAsJsonObject(); Set<String> keys = jsonObject.keySet(); StringBuilder sb = new StringBuilder(); for (String key : keys) { String encode = URLEncoder.encode(jsonObject.get(key).getAsString(), "UTF-8"); sb.append(key).append("=").append(encode).append("&"); } return sb.toString(); } }
package com.zxz.framework.utils; import java.nio.charset.StandardCharsets; import java.util.Base64; /** * Base64转码工具类 */ public class Base64Util { public static byte[] encode(byte[] bytes) { return Base64.getEncoder().encode(bytes); } public static byte[] encode(String str) { return Base64.getEncoder().encode(str.getBytes(StandardCharsets.UTF_8)); } public static String encodeToString(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); } public static String encodeToString(String str) { return Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8)); } public static byte[] decode(byte[] bytes) { return Base64.getDecoder().decode(bytes); } public static byte[] decode(String str) { return Base64.getDecoder().decode(str); } public static String decodeToString(byte[] bytes) { byte[] decode = Base64.getDecoder().decode(bytes); return new String(decode); } public static String decodeToString(String str) { byte[] decode = Base64.getDecoder().decode(str); return new String(decode); } }
package com.zxz.framework.utils; import com.alibaba.fastjson.JSON; import java.util.List; /** * JSON统一工具类 */ public class JsonUtil { /** * java对象转json字符串 * @param object * @return */ public static String toJson(Object object) { return JSON.toJSONString(object); } /** * json字符串转换为T类型的对象 * @param text json字符串 * @param tClass T的class * @return T对象 */ public static <T> T parseObject(String text, Class<T> tClass) { return JSON.parseObject(text, tClass); } /** * json字符串转Object * @param text json字符串 * @return Object */ public static Object parse(String text) { return JSON.parse(text); } /** * json转list对象 * @param text list类型的json字符串 * @param tClass 返回类型的class * @param <T> 返回集合泛型 * @return list */ public static <T> List<T> parseArray(String text, Class<T> tClass) { return JSON.parseArray(text, tClass); } }
package com.zxz.framework.utils; import org.springframework.util.DigestUtils; import java.nio.charset.StandardCharsets; /** * MD5编码工具 */ public class MD5Util { public static String encode(String str) { return DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8)); } public static String encode(byte[] bytes) { return DigestUtils.md5DigestAsHex(bytes); } }
package com.zxz.framework.utils; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; public class RSAEncrypt { private static final int KEY_SIZE = 1024; private static final String RSA_ALGORITHM = "RSA"; // RSA最大加密明文大小 private static final int MAX_ENCRYPT_LENGTH = 117; // RSA最大解密明文大小 private static final int MAX_DECRYPT_LENGTH = 128; /*// 测试加解密 public static void main(String[] args) { Map<String, String> keyPair = RSAEncrypt.getKeyPair(); String publicKey = keyPair.get("publicKey"); String privateKey = keyPair.get("privateKey"); System.out.println(publicKey); System.out.println(privateKey); String zxz = RSAEncrypt.encrypt("zxz", publicKey); System.out.println("加密后数据:"+zxz); String decrypt = RSAEncrypt.decrypt(zxz, privateKey); System.out.println("解密后数据:"+decrypt); }*/ /** * 随机生成密钥对 * @return 密钥对map */ public static Map<String, String> getKeyPair() { HashMap<String, String> keyPairMap = new HashMap<>(); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM); keyPairGenerator.initialize(KEY_SIZE); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); keyPairMap.put("publicKey", encodeBase64(publicKey.getEncoded())); keyPairMap.put("privateKey", encodeBase64(privateKey.getEncoded())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return keyPairMap; } /** * 分段加密 * @param str 需要加密的字符串 * @param publicKey 加密的公钥 */ public static String encrypt(String str, String publicKey) { String outStr = null; try { byte[] publicKeyBytes = decodeBase46(publicKey); byte[] data = str.getBytes(StandardCharsets.UTF_8); KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM); PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes)); Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, pubKey); ByteArrayOutputStream out = new ByteArrayOutputStream(); int inputLen = data.length; int offset = 0; int i = 0; byte[] cache; while (inputLen > offset) { int len = Math.min(inputLen - offset, MAX_ENCRYPT_LENGTH); cache = cipher.doFinal(data, offset, len); out.write(cache, 0, cache.length); i++; offset = i * MAX_ENCRYPT_LENGTH; } byte[] outBytes = out.toByteArray(); outStr = encodeBase64(outBytes); } catch (Exception e) { e.printStackTrace(); } return outStr; } /** * 分段解密 * @param str 需要解码的字符串(是经过base64编码的) * @param privateKey 解码用的私钥 */ public static String decrypt(String str, String privateKey) { byte[] data = decodeBase46(str); byte[] privateKeyBytes = decodeBase46(privateKey); String outStr = null; try { KeyFactory instance = KeyFactory.getInstance(RSA_ALGORITHM); PrivateKey priKey = instance.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, priKey); ByteArrayOutputStream out = new ByteArrayOutputStream(); int inputLen = data.length; int offset = 0; int i = 0; byte[] cache; while (inputLen > offset) { int len = Math.min(inputLen - offset, MAX_DECRYPT_LENGTH); cache = cipher.doFinal(data, offset, len); out.write(cache, 0, cache.length); i++; offset = i * MAX_DECRYPT_LENGTH; } byte[] outBytes = out.toByteArray(); outStr = new String(outBytes); } catch (Exception e) { e.printStackTrace(); } return outStr; } /** * RSA加密 * @param str 需要加密的字符串 * @param publicKey 加密的公钥 */ public static String encryptNoSegment(String str, String publicKey) { String outStr = null; try { byte[] publicKeyBytes = decodeBase46(publicKey); KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM); PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes)); Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] bytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)); outStr = encodeBase64(bytes); } catch (Exception e) { e.printStackTrace(); } return outStr; } /** * * @param str 需要解码的字符串(是经过base64编码的) * @param privateKey 解码用的私钥 * @return */ public static String decryptNoSegment(String str, String privateKey) { byte[] bytes = decodeBase46(str); byte[] privateKeyBytes = decodeBase46(privateKey); String outStr = null; try { KeyFactory instance = KeyFactory.getInstance(RSA_ALGORITHM); PrivateKey priKey = instance.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, priKey); outStr = new String(cipher.doFinal(bytes)); } catch (Exception e) { e.printStackTrace(); } return outStr; } /** * base64编码 * @param encoded 需要编码的字节数组 * @return base64字符串 */ private static String encodeBase64(byte[] encoded) { return Base64Util.encodeToString(encoded); } /** * base64解码成字节数组 * @param base64String base64字符串 * @return 解码出的字节数组 */ private static byte[] decodeBase46(String base64String) { return Base64Util.decode(base64String); } }
package com.zxz.framework.utils; import com.zxz.framework.advice.Result; import com.zxz.framework.advice.ResultCode; import org.springframework.http.HttpStatus; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Servlet工具类 */ public class ServletUtil { /** * 获取请求对象 request * @return HttpServletRequest */ public static HttpServletRequest getRequest() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes; assert servletRequestAttributes != null; return servletRequestAttributes.getRequest(); } /** * 获取响应对象 response * @return HttpServletResponse */ public static HttpServletResponse getResponse() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes; assert servletRequestAttributes != null; return servletRequestAttributes.getResponse(); } /** * 响应给客户端数据 * @param resultCode 响应结果枚举 */ public static void response(ResultCode resultCode) { Result result = Result.fail(resultCode); response(result); } /** * 响应给客户端数据 * @param result 统一返回值对象 */ public static void response(Result result) { HttpServletResponse response = getResponse(); response.setStatus(HttpStatus.OK.value()); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); try { response.getWriter().println(JsonUtil.toJson(result)); } catch (IOException e) { e.printStackTrace(); } } }
package com.zxz.framework.utils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; /** * @ClassName: TreeUtil * @Description: 构建树形使用的方法 */ public class TreeUtil { /** * 构建树形数据 * @param treeNodes 具有父子关系的list数据 * @param <T> 泛型 * @return List<T> tree */ public static <T extends TreeNode<T>> List<T> build(List<T> treeNodes) { List<T> rootNodes = getRootNodes(treeNodes); List<T> tree = new ArrayList<>(); for (T rootNode : rootNodes) { buildChildNodes(rootNode, treeNodes); tree.add(rootNode); } return tree; } /** * 给节点挂载子节点数据 * @param node 节点 * @param treeNodes 具有父子关系的list数据 * @param <T> 数据类型 * @return T */ private static <T extends TreeNode<T>> T buildChildNodes(T node, List<T> treeNodes) { List<T> childNodes = new ArrayList<>(); for (T treeNode : treeNodes) { if (isEquals(node.getId(), treeNode.getParentId())) { childNodes.add(buildChildNodes(treeNode, treeNodes)); } } if (childNodes.size() > 0) { node.setChildList(childNodes); } return node; } /** * 获取根节点list数据 * @param treeNodes 根节点数据 * @param <T> 数据泛型 * @return List<T> */ private static <T extends TreeNode<T>> List<T> getRootNodes(List<T> treeNodes) { List<T> rootNodes = new ArrayList<>(); List<Object> ids = treeNodes.stream().map(TreeNode::getId).collect(Collectors.toList()); Iterator<T> iterator = treeNodes.iterator(); while (iterator.hasNext()) { T next = iterator.next(); Object parentId = next.getParentId(); if (parentId == null || parentId.equals(0) || !ids.contains(parentId)) { rootNodes.add(next); iterator.remove(); } } return rootNodes; } /** * 判断两个对象是否相等 */ private static boolean isEquals(Object pid, Object parentId) { boolean isEquals = true; if (pid != null && !pid.equals(parentId)) isEquals = false; if (parentId != null && !parentId.equals(pid)) isEquals = false; return isEquals; } }
package com.zxz.framework.utils; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Redis工具类 */ @Component("redisUtil") public class RedisUtil { // 验证码key前缀 public static final String PREFIX_VERIFICATION = "verification"; // 用户key前缀 public static final String PREFIX_USER = "user"; // 所有菜单集合的key值 public static final String KEY_ALL_MENU_LIST = "menu:all:list"; // 角色id拥有菜单key前缀 public static final String PREFIX_ROLE_ID_MENU = "menu:roleId"; // 角色拥有菜单key前缀 public static final String PREFIX_ROLE_MENU = "menu:role"; @Resource private StringRedisTemplate stringRedisTemplate; /** * 保存对象到redis中,默认过期时间30分钟 * @param key 键 * @param value 值 */ public void set(String key, Object value) { set(key, value, 30L, TimeUnit.MINUTES); } /** * 保存对象到redis中 * @param key 键 * @param value 值 * @param expires 过期时间(Long) * @param timeUnit 时间单位 */ public void set(String key, Object value, Long expires, TimeUnit timeUnit) { String val = JsonUtil.toJson(value); if (value instanceof String) { val = (String) value; } stringRedisTemplate.opsForValue().set(key, val, expires, timeUnit); } /** * 获取redis中的String类型的值 * @param key * @return String */ public String get(Object key) { return stringRedisTemplate.opsForValue().get(key); } /** * 获取redis中存储的对象 * @param key 键 * @param tClass 获取对象类型class * @param <T> 泛型 * @return T */ public <T> T get(Object key, Class<T> tClass) { String value = stringRedisTemplate.opsForValue().get(key); if (!StringUtils.hasText(value)) { return null; } return JsonUtil.parseObject(value, tClass); } /** * 存储list数据到redis缓存 * @param key 缓存的key值 * @param list list数据 * @param expires 过期时间 * @param timeUnit 过期时间单位 */ public <T> void setList(String key, List<T> list, Long expires, TimeUnit timeUnit) { String value = JsonUtil.toJson(list); set(key, value, expires, timeUnit); } /** * 获取redis中存储的集合数据 * @param key 缓存的key值 * @param tClass 获取对象类型class * @param <T> 泛型 * @return List<T> */ public <T> List<T> getList(Object key, Class<T> tClass) { try { String value = get(key); if (StringUtils.hasText(value)) { return JsonUtil.parseArray(value, tClass); } return null; } catch (Exception e) { return null; } } /** * 删除redis中的对象 * @param key 键 * @return Boolean */ public Boolean delete(String key) { return stringRedisTemplate.delete(key); } /** * 获取对象并重新设置过期时间 * @param key 鍵 * @param expires 过期时间(Long) * @param timeUnit 过期时间单位 */ public String getAndExpire(String key, Long expires, TimeUnit timeUnit) { // return stringRedisTemplate.opsForValue().getAndExpire(key, expires, timeUnit); stringRedisTemplate.expire(key, expires, timeUnit); return get(key); } /** * 获取缓存的key值 * @param val key的部分 * @return 组装出来的key值 */ public String getKey(String... val) { return String.join(":", val); } }
package com.zxz.study.util; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.HashMap; import java.util.Map; public class DownloadUtil { public static void download(File file, HttpServletRequest request, HttpServletResponse response) { download(file, "", request, response); } /** * 支持断点续传的下载文件 * @param file 文件 * @param fileName 下载名称 * @param request * @param response */ public static void download(File file, String fileName, HttpServletRequest request, HttpServletResponse response) { if (fileName == null || "".equals(fileName)) { fileName = file.getName(); } long length = file.length(); // 1.解析Range参数 String range = request.getHeader("Range"); System.out.println("range==> "+range); Map<String, Long> map = getFromAndTo(range); Long from = map.get("from"); Long to = map.get("to"); if (from == null) { from = 0L; } if (to == null) { to = length - 1; } // 2.设置返回的状态值(200:全部处理,206:部分处理) if (from == 0 && to == length - 1) { response.setStatus(200); } else { response.setStatus(206); } // 3.设置响应头 response.setHeader("Accept-Ranges", "bytes"); String contentRange = "bytes="+from+"-"+to+"/"+length; response.setHeader("Content-Range", contentRange); // 4.设置编码格式 response.setCharacterEncoding("utf-8"); response.setContentType("application/octet-stream;charset=GBK"); // 5.设置文件下载名需要编码ISO-8859-1 try { fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); // 6.输出流 ServletOutputStream outputStream = null; FileInputStream fis = null; BufferedInputStream bis = null; try { outputStream = response.getOutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); if (from > 0) { bis.skip(from); } byte[] buffer = new byte[100 * 1024]; int len = 0; while ((len = bis.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } outputStream.flush(); } catch (IOException e) { // e.printStackTrace(); } finally { try { bis.close(); } catch (IOException e) { // e.printStackTrace(); } try { fis.close(); } catch (IOException e) { // e.printStackTrace(); } } } /** * 解析断点续传的 Range参数 * @param range Range参数 * @return map (key值"from", "to") */ private static Map<String, Long> getFromAndTo(String range) { Map<String, Long> map = new HashMap<>(); map.put("from", null); map.put("to", null); if (range != null) { String[] array = range.split("=|-"); if (array.length >= 2) { String from = array[1].trim(); if (!from.isEmpty()) { map.put("from", Long.parseLong(from)); } if (array.length >= 3) { String to = array[2].trim(); if (!to.isEmpty()) { map.put("to", Long.parseLong(to)); } } } } return map; } }
package cn.com.zetatech.cloud.dmo.spc.service.util; import cn.com.zetatech.cloud.dmo.spc.common.ErrorCode; import cn.com.zetatech.cloud.sf.service.common.BusinessException; import cn.hutool.core.collection.CollectionUtil; import lombok.Data; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFont; import org.springframework.core.io.ClassPathResource; import javax.imageio.ImageIO; import java.awt.Color; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class ExcelToImage { public static void main(String[] args) { ClassPathResource classPathResource = new ClassPathResource("/templates/push/statWay1.xlsx"); InputStream inputStream = null; try { inputStream = classPathResource.getInputStream(); Workbook wb = WorkbookFactory.create(inputStream); Sheet sheet = wb.getSheetAt(0); List<CellRangeAddress> rangeAddress = sheet.getMergedRegions(); // 获取整个sheet中合并单元格组合的集合 // 首先做初步的边界检测,如果指定区域是不合法的则抛出异常 int rowSum = sheet.getLastRowNum(); int colSum = sheet.getRow(0).getLastCellNum(); int imageWidth = 0; int imageHeight = 0; List<Grid> grids = new ArrayList<>(); int tempY = 0; for (int i = 0; i < rowSum; i++) { float physicalNumberOfCells = sheet.getRow(i).getHeightInPoints(); int height = Math.round(physicalNumberOfCells); int tempX = 0; for (int j = 0; j < colSum; j++) { Cell cell = sheet.getRow(i).getCell(j); CellStyle cellStyle = cell.getCellStyle(); // 背景色 Color bgColor = getBgColor(cellStyle); Color ftColor = getFtColor(wb, cellStyle); float columnWidthInPixels = sheet.getColumnWidthInPixels(j); int width = Math.round(columnWidthInPixels); // 获取格子的文字 String text = getValueFromCell(cell); Grid grid = new Grid(); int[] mergeInfo = getMergeInfo(rangeAddress, i, j); if (mergeInfo[0] == -1) { grid.setBgColor(bgColor); grid.setFtColor(ftColor); // 此时不属于合并的格子 grid.setX(tempX); grid.setY(tempY); grid.setHeight(height); grid.setWidth(width); grid.setContent(text); grids.add(grid); } else { int firstRow = mergeInfo[0]; int lastRow = mergeInfo[1]; int firstCol = mergeInfo[2]; int lastCol = mergeInfo[3]; if (firstRow == i && firstCol == j) { grid.setBgColor(bgColor); grid.setFtColor(ftColor); // 是第一个合并格子 grid.setX(tempX); grid.setY(tempY); int h = 0; for (int i1 = firstRow; i1 <= lastRow; i1++) { h += Math.round(sheet.getRow(i1).getHeightInPoints()); } int w = 0; for (int i1 = firstCol; i1 <= lastCol; i1++) { w += Math.round(sheet.getColumnWidthInPixels(i1)); } grid.setHeight(h); grid.setWidth(w); grid.setContent(text); grids.add(grid); } } tempX += width; } tempY += height; imageHeight = tempY; imageWidth = tempX; } int scale = 2; imageWidth = (imageWidth + 20) * scale; imageHeight = (imageHeight + 20) * scale; BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); g2d.scale(scale, scale); // 平滑字体 g2d.setColor(Color.white); g2d.fillRect(0, 0, imageWidth, imageHeight); // 绘制格子 for (Grid grid : grids) { int x = grid.getX() + 10; int y = grid.getY() + 10; int width = grid.getWidth(); int height = grid.getHeight(); String content = grid.getContent(); Color bgColor = grid.getBgColor(); Color ftColor = grid.getFtColor(); // 绘制背景色 g2d.setColor(bgColor == null ? Color.white : bgColor); g2d.fillRect(x, y, width, height); // 绘制边框 g2d.setColor(Color.black); g2d.setStroke(new BasicStroke(1f / scale)); g2d.drawRect(x, y, width, height); // 绘制文字,居中显示 g2d.setColor(ftColor == null ? Color.black : ftColor); FontMetrics fm = g2d.getFontMetrics(); int fontSize = fm.getFont().getSize(); int strWidth = fm.stringWidth(content);// 获取将要绘制的文字宽度 g2d.drawString(content, x + (width - strWidth) / 2, y + (height - fontSize) / 2 + fontSize); } g2d.dispose(); ImageIO.write(image, "png", new File("D:/test.png")); } catch (IOException e) { throw new BusinessException(ErrorCode.CODE_EXCEPTION_OCCURED, "加载定制工序参数错误"); } finally { try { assert inputStream != null; inputStream.close(); } catch (IOException ignored) {} } } private static Color getFtColor(Workbook wb, CellStyle cellStyle) { org.apache.poi.ss.usermodel.Font font = wb.getFontAt(cellStyle.getFontIndexAsInt()); if (font instanceof XSSFFont) { XSSFFont xf = (XSSFFont) font; XSSFColor xssfColor = xf.getXSSFColor(); if (xssfColor != null) { byte[] rgb = xssfColor.getRGBWithTint(); if (rgb != null) { int r = (rgb[0] + 256) % 256; int g = (rgb[1] + 256) % 256; int b = (rgb[2] + 256) % 256; return new Color(r , g, b); } } } return Color.BLACK; } private static Color getBgColor(CellStyle cellStyle) { org.apache.poi.ss.usermodel.Color color1 = cellStyle.getFillForegroundColorColor(); if (color1 != null) { if (color1 instanceof XSSFColor) { byte[] rgb = ((XSSFColor) color1).getRGBWithTint(); if (rgb != null) { int r = (rgb[0] + 256) % 256; int g = (rgb[1] + 256) % 256; int b = (rgb[2] + 256) % 256; return new Color(r , g, b); } } } return Color.WHITE; } private static int[] getMergeInfo(List<CellRangeAddress> rangeAddress, int rowIndex, int colIndex) { int[] mergeArr = {-1, -1, -1, -1}; if (CollectionUtil.isEmpty(rangeAddress)) return mergeArr; for (CellRangeAddress address : rangeAddress) { int firstRow = address.getFirstRow(); int lastRow = address.getLastRow(); int firstCol = address.getFirstColumn(); int lastCol = address.getLastColumn(); if (rowIndex >= firstRow && rowIndex <= lastRow && colIndex >= firstCol && colIndex <= lastCol) { mergeArr = new int[]{firstRow, lastRow, firstCol, lastCol}; } } return mergeArr; } private static boolean isMergeGrid(List<CellRangeAddress> rangeAddress, int rowIndex, int colIndex) { if (CollectionUtil.isEmpty(rangeAddress)) return false; for (CellRangeAddress address : rangeAddress) { int firstRow = address.getFirstRow(); int lastRow = address.getLastRow(); int firstCol = address.getFirstColumn(); int lastCol = address.getLastColumn(); if (rowIndex >= firstRow && rowIndex <= lastRow && colIndex >= firstCol && colIndex <= lastCol) { return true; } } return false; } private static String getValueFromCell(Cell cell) { CellType cellType = cell.getCellType(); if (cellType == CellType.STRING) { return cell.getStringCellValue(); } if (cellType == CellType.NUMERIC) { return String.valueOf(cell.getNumericCellValue()); } if (cellType == CellType.BOOLEAN) { return String.valueOf(cell.getBooleanCellValue()); } if (cellType == CellType.FORMULA) { try { return String.valueOf(cell.getNumericCellValue()); } catch (Exception e) { return String.valueOf(cell.getRichStringCellValue()); } } return ""; } @Data static class Grid{ private int x; private int y; private int width; private int height; private String content; private Color bgColor; private Color ftColor; } }
作者:[一柒微笑]