工具类

package com.sapit.compensation.moudle;import java.awt.Color;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.BorderStyle;
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.ss.util.CellRangeAddress;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextBox;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.alibaba.fastjson.JSONObject;
import com.sapit.compensation.common.util.Base64Util;
import com.sapit.compensation.common.util.FileUtilsExt;
import com.sapit.compensation.common.util.TimestampTool;
import com.sapit.compensation.common.util.ZipUtils;
import com.sapit.compensation.moudle.business.architectureAnalysis.SchemeAnalysis;
import com.sapit.compensation.moudle.business.data.CompensationAnalysis;/*** <p>文件名称: DownloadEcharsAndData.java </p> * <p>类型描述: [分析页面下载功能] </p>* <p>创建时间: 2022年5月23日 </p>* @author jlk* @version V1.0*/
public class DownloadEcharsAndData {private static Logger logger = LoggerFactory.getLogger(com.sapit.compensation.common.util.FileUtilsExt.class);/*** @Description: 下载zip* @param <map>* @param <HttpServletResponse>* @Author:jlk* @CreateTime:2022-05-24* @throws IOException */@SuppressWarnings("all")public static void downloadZip(HashMap map, HttpServletRequest request, HttpServletResponse response) throws IOException {String path = request.getSession().getServletContext().getRealPath("upload");String fileName = UUID.randomUUID().toString();File file = new File(path + File.separator + fileName);response.setContentType("application/zip");response.setCharacterEncoding("utf-8");response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(map.get("name").toString(), "UTF-8"));OutputStream outs = response.getOutputStream();try {if (file.mkdirs()) {logger.debug("生成文件夹成功", file.toString());}//excel生成String excelPath = "";//initCellMaxTextLength();if (map.get("customerPositionClass") != null) {excelPath = writeExcelCustomerPositionClass(file, map);} else {excelPath = writeExcel(file, map);}//转码图片List<String> imgPathList = base64ToJpg(file, map);//打包zipList<File> fileList = new ArrayList<>();if (CollectionUtils.isNotEmpty(imgPathList)) {for (int i = 0; i < imgPathList.size(); i++) {fileList.add(new File(imgPathList.get(i)));}}if (StringUtils.isNoneBlank(excelPath))fileList.add(new File(excelPath));ZipUtils.toZip(fileList, outs);} catch (Exception e) {logger.debug("错误", e);} finally {outs.flush();outs.close();FileUtilsExt.delFile(file.toString());}}/*** @Description: base64转换jpg* @param <File>* @param <HashMap>* @throws IOException * @Author:jlk* @CreateTime:2022-05-24*/@SuppressWarnings("all")public static List<String> base64ToJpg(File file, HashMap map) throws IOException {List<String> imgPathList = new ArrayList<String>();if (map.get("baseImg") != null) {List<String> imgList = (List<String>) map.get("baseImg");for (int i = 0; i < imgList.size(); i++) {String base64 = imgList.get(i);if (StringUtils.isNotBlank(base64)) {String imgPathName = file.toString() + File.separator + map.get("name") + "_图表_" + i;String imgPath = Base64Util.generateImage(base64, imgPathName);imgPathList.add(imgPath);}}return imgPathList;}return imgPathList;}/*** @Description: excel* @param <File>* @param <HashMap>* @Author:jlk* @CreateTime:2022-05-24*/@SuppressWarnings("all")public static String writeExcel(File file, HashMap map) throws IOException {//服务器路径+文件名String excelPath = file.toString() + file.separator + map.get("name") + ".xlsx";FileOutputStream fout = new FileOutputStream(excelPath);try {//获取数据源List<List<String>> dataList = (List<List<String>>) map.get("dataList");List<List<String>> colorList = (List<List<String>>) map.get("colorList");List<List<String>> titleList = (List<List<String>>) map.get("titleList");List<List<String>> echarsList = (List<List<String>>) map.get("echarsList");List<List<String>> dataRatioList = (List<List<String>>) map.get("dataRatioList");List<List<String>> colorRatioList = (List<List<String>>) map.get("colorRatioList");//创建excelXSSFWorkbook wb = new XSSFWorkbook();XSSFRow row = null;XSSFCell cell = null;// 创建新的sheet对象(excel的表单) 并设置sheet名字XSSFSheet sheet = wb.createSheet(map.get("name").toString());sheet.setDefaultRowHeightInPoints(20);sheet.setDefaultColumnWidth(12);XSSFCellStyle titleStyle = getTitleStyle(wb);XSSFCellStyle echarsStyle = getEcharsStyle(wb);XSSFCellStyle cellNoColorStyle = getNoColorStyle(wb);Font cellFont = wb.createFont();cellFont.setItalic(false); // 设置字体为斜体字   cellFont.setFontHeightInPoints((short) 10); // 将字体大小设置为9px   cellFont.setFontName("宋体"); // 字体应用到当前单元格上   cellNoColorStyle.setFont(cellFont);cellNoColorStyle.setWrapText(true);//设置自动换行// ------------------处理数据/start---------------------//表头int rowNum = 0;if (CollectionUtils.isNotEmpty(titleList)) {for (int i = 0; i < titleList.size(); i++) {int MergedCount = 0;int beginIndex = 0;int endIndex = 0;row = sheet.createRow(rowNum);rowNum++;List<String> titles = titleList.get(i);for (int j = 0; j < titles.size(); j++) {String content = titles.get(j);cell = row.createCell(j);cell.setCellValue("" + content + "");cell.setCellStyle(titleStyle);if (j > 0 && j < titles.size()) {if (content.equals(titles.get(j - 1)) && StringUtils.isNotBlank(content)) {MergedCount++;if (MergedCount == 1) {beginIndex = j - 1;}if (j == titles.size() - 1) {endIndex = j;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), beginIndex, endIndex));}} else if (!content.equals(titles.get(j - 1)) && MergedCount > 0 && j == titles.size() - 1) {endIndex = j - 1;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), beginIndex, endIndex));}}if (i > 0 && i < titleList.size()) {String contentRow = titleList.get(i - 1).get(j);if (i > 0 && i < titleList.size() && contentRow.equals(titles.get(j))) {sheet.addMergedRegion(new CellRangeAddress(row.getRowNum() - 1, row.getRowNum(), j, j));}}}}}//表格数据if (CollectionUtils.isNotEmpty(colorList)) {for (int i = 0; i < dataList.size(); i++) {row = sheet.createRow(rowNum);rowNum++;List<String> rowColorList = colorList.get(i);List<String> rowList = dataList.get(i);for (int j = 0; j < rowList.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + rowList.get(j) + "");XSSFCellStyle cellColorStyle = wb.createCellStyle();String color = rowColorList.get(j);cellColorStyle.setAlignment(HorizontalAlignment.CENTER);cellColorStyle.setVerticalAlignment(VerticalAlignment.CENTER);cellColorStyle.setBorderBottom(BorderStyle.THIN);//下边框  cellColorStyle.setBorderLeft(BorderStyle.THIN);//左边框  cellColorStyle.setBorderRight(BorderStyle.THIN);//右边框  cellColorStyle.setBorderTop(BorderStyle.THIN);//上边框cellColorStyle.setFont(cellFont);cellColorStyle.setWrapText(true);//设置自动换行cellColorStyle.setFillForegroundColor(new XSSFColor(new Color(colorToFloat(color)[0], colorToFloat(color)[1], colorToFloat(color)[2])));cellColorStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);cell.setCellStyle(cellColorStyle);}}} else {for (int i = 0; i < dataList.size(); i++) {row = sheet.createRow(rowNum);rowNum++;List<String> rowList = dataList.get(i);for (int j = 0; j < rowList.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + rowList.get(j) + "");cell.setCellStyle(cellNoColorStyle);}}}if (CollectionUtils.isNotEmpty(dataRatioList)) {rowNum = rowNum + 5;if (CollectionUtils.isNotEmpty(titleList)) {for (int i = 0; i < titleList.size(); i++) {int MergedCount = 0;int beginIndex = 0;int endIndex = 0;row = sheet.createRow(rowNum);rowNum++;List<String> titles = titleList.get(i);for (int j = 0; j < titles.size(); j++) {String content = titles.get(j);cell = row.createCell(j);cell.setCellValue("" + content + "");cell.setCellStyle(titleStyle);if (j > 0 && j < titles.size()) {if (content.equals(titles.get(j - 1)) && StringUtils.isNotBlank(content)) {MergedCount++;if (MergedCount == 1) {beginIndex = j - 1;}if (j == titles.size() - 1) {endIndex = j;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), beginIndex, endIndex));}} else if (!content.equals(titles.get(j - 1)) && MergedCount > 0 && j == titles.size() - 1) {endIndex = j - 1;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), beginIndex, endIndex));}}if (i > 0 && i < titleList.size()) {String contentRow = titleList.get(i - 1).get(j);if (i > 0 && i < titleList.size() && contentRow.equals(titles.get(j))) {sheet.addMergedRegion(new CellRangeAddress(row.getRowNum() - 1, row.getRowNum(), j, j));}}}}}//表格二数据if (CollectionUtils.isNotEmpty(colorRatioList)) {for (int i = 0; i < dataRatioList.size(); i++) {row = sheet.createRow(rowNum);rowNum++;List<String> rowColorList = colorRatioList.get(i);List<String> rowList = dataRatioList.get(i);for (int j = 0; j < rowList.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + rowList.get(j) + "");XSSFCellStyle cellColorStyle = wb.createCellStyle();String color = rowColorList.get(j);cellColorStyle.setAlignment(HorizontalAlignment.CENTER);cellColorStyle.setVerticalAlignment(VerticalAlignment.CENTER);cellColorStyle.setBorderBottom(BorderStyle.THIN);//下边框  cellColorStyle.setBorderLeft(BorderStyle.THIN);//左边框  cellColorStyle.setBorderRight(BorderStyle.THIN);//右边框  cellColorStyle.setBorderTop(BorderStyle.THIN);//上边框cellColorStyle.setFont(cellFont);cellColorStyle.setWrapText(true);//设置自动换行cellColorStyle.setFillForegroundColor(new XSSFColor(new Color(colorToFloat(color)[0], colorToFloat(color)[1], colorToFloat(color)[2])));cellColorStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);cell.setCellStyle(cellColorStyle);}}} else {for (int i = 0; i < dataRatioList.size(); i++) {row = sheet.createRow(rowNum);rowNum++;List<String> rowList = dataRatioList.get(i);for (int j = 0; j < rowList.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + rowList.get(j) + "");cell.setCellStyle(cellNoColorStyle);}}}}//echars数据if (rowNum != 0) {rowNum = rowNum + 5;}if (CollectionUtils.isNotEmpty(echarsList)) {for (int i = 0; i < echarsList.size(); i++) {List<String> echars = echarsList.get(i);if (CollectionUtils.isNotEmpty(echars)) {for (int j = 0; j < echars.size(); j++) {row = sheet.createRow(rowNum);String content = echars.get(j);if (StringUtils.isNoneBlank(content)) {int max = 32767;int len = content.length();int num = content.length() / max;for (int k = 0; k <= num; k++) {if (k == num) {cell = row.createCell(k);cell.setCellValue("" + content.substring(k * max, len) + "");cell.setCellStyle(echarsStyle);} else {cell = row.createCell(k);cell.setCellValue("" + content.substring(k * max, (k + 1) * max) + "");cell.setCellStyle(echarsStyle);}}}rowNum++;}}}}// ------------------处理数据end--------------------------------------wb.write(fout);fout.close();} catch (Exception e) {e.printStackTrace();} finally {}return excelPath;}/*** @Description: rgb颜色值转换* @param <String>* @Author:jlk* @CreateTime:2022-05-24*/@SuppressWarnings("all")public static Integer[] colorToFloat(String color) {Integer[] rgb = Arrays.stream(color.split(",")).map(s -> {s = s.trim();return Integer.parseInt(s);}).toArray(Integer[]::new);return rgb;}/*** @Description: 下载PPT* @param <map>* @param <HttpServletResponse>* @Author:jlk* @CreateTime:2022-05-24* @throws IOException */@SuppressWarnings("all")public static void downloadPPT(String customerName, List<CompensationAnalysis> CompensationAnalysisList, HttpServletRequest request,HttpServletResponse response) throws IOException {String path = request.getSession().getServletContext().getRealPath("upload");String fileName = UUID.randomUUID().toString();File file = new File(path + File.separator + fileName);if (file.mkdirs()) {logger.debug("生成文件夹成功", file.toString());}response.reset();response.setContentType("application/zip");response.setCharacterEncoding("utf-8");response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(customerName + "_薪酬分析图表_" + TimestampTool.getDate(new Date()), "UTF-8"));OutputStream outs = response.getOutputStream();//创建pptXMLSlideShow ppt = new XMLSlideShow();File pptPath = new File(file + File.separator + customerName + "_薪酬分析图表_" + TimestampTool.getDate(new Date()) + ".pptx");Map<Integer, String> dataMap = new HashMap<>();FileOutputStream pptbaos = new FileOutputStream(pptPath);//创建excelXSSFWorkbook wb = new XSSFWorkbook();File excelPath = new File(file + File.separator + customerName + "_薪酬分析图表_" + TimestampTool.getDate(new Date()) + ".xlsx");FileOutputStream excelbaos = new FileOutputStream(excelPath);boolean isppt = false;boolean isexcel = false;try {for (int j = 0; j < CompensationAnalysisList.size(); j++) {String base64 = CompensationAnalysisList.get(j).getAnalysisImage();String data = CompensationAnalysisList.get(j).getAnalysisData();String name = CompensationAnalysisList.get(j).getAnalysisTopicName();if (StringUtils.isNotBlank(base64)) {XSLFSlide slide = ppt.createSlide();XSLFTextBox shape1 = slide.createTextBox();Rectangle anchor = new Rectangle(30, 30, 300, 50);shape1.setAnchor(anchor);XSLFTextParagraph p1 = shape1.addNewTextParagraph();XSLFTextRun r1 = p1.addNewTextRun();r1.setFontSize(14.00);r1.setFontColor(Color.black);//shape1.setFillColor(Color.red);  r1.setText(name);// 图片文件String imgPathName = file.toString() + File.separator + CompensationAnalysisList.get(j).getAnalysisTopicName();String imgPath = Base64Util.generateImage(base64, imgPathName);File image = new File(imgPath);//测试用本地图片//File image = new File("E://plief.jpg");// 图片文件输入流FileInputStream imageFis = new FileInputStream(image);// 获取图片大小int len = (int) image.length();// 创建一个字节数组,数组大小与图片文件大小一致byte[] imageData = new byte[len];// 将图片数据读进字节数组中int pictureData = imageFis.read(imageData);// 将图片添加到PPT中XSLFPictureData pd = ppt.addPicture(imageData, PictureType.PNG);// 将图片放到指定的幻灯片中XSLFPictureShape pic = slide.createPicture(pd);// 设置图片框的放置的位置和大小pic.setAnchor(new Rectangle2D.Double(100, 160, 520, 200));isppt = true;imageFis.close();}if (StringUtils.isNotBlank(data)) {JSONObject object = JSONObject.parseObject(data);writeExcel(object, wb);isexcel = true;}}ppt.write(pptbaos);wb.write(excelbaos);List<File> fileList = new ArrayList<>();if (isppt)fileList.add(pptPath);if (isexcel)fileList.add(excelPath);ZipUtils.toZip(fileList, outs);} catch (Exception e) {logger.debug("错误", e);} finally {pptbaos.flush();pptbaos.close();excelbaos.flush();excelbaos.close();outs.flush();outs.close();FileUtilsExt.delFile(file.toString());}}public static byte[] File2byte(File tradeFile) {byte[] buffer = null;try {FileInputStream fis = new FileInputStream(tradeFile);ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] b = new byte[1024];int n;while ((n = fis.read(b)) != -1) {bos.write(b, 0, n);}fis.close();bos.close();buffer = bos.toByteArray();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return buffer;}public static XSLFSlide copySlide(XSLFSlide slide) {XSLFSlide newSlide = slide.getSlideShow().createSlide(slide.getSlideLayout());newSlide.appendContent(slide);return newSlide;}/*** @Description: excel* @param <File>* @param <HashMap>* @Author:jlk* @CreateTime:2022-05-24*/@SuppressWarnings("all")public static XSSFWorkbook writeExcel(JSONObject jsonObject, XSSFWorkbook wb) throws IOException {try {//获取数据源List<List<String>> dataList = (List<List<String>>) jsonObject.get("dataList");List<List<String>> colorList = (List<List<String>>) jsonObject.get("colorList");List<List<String>> titleList = (List<List<String>>) jsonObject.get("titleList");List<List<String>> echarsList = (List<List<String>>) jsonObject.get("echarsList");List<List<String>> dataRatioList = (List<List<String>>) jsonObject.get("dataRatioList");List<List<String>> colorRatioList = (List<List<String>>) jsonObject.get("colorRatioList");XSSFRow row = null;XSSFCell cell = null;// 创建新的sheet对象(excel的表单) 并设置sheet名字XSSFSheet sheet = wb.createSheet(jsonObject.get("name").toString());sheet.setDefaultRowHeightInPoints(20);sheet.setDefaultColumnWidth(12);XSSFCellStyle titleStyle = getTitleStyle(wb);XSSFCellStyle echarsStyle = getEcharsStyle(wb);XSSFCellStyle cellNoColorStyle = getNoColorStyle(wb);Font cellFont = wb.createFont();cellFont.setItalic(false); // 设置字体为斜体字   cellFont.setFontHeightInPoints((short) 10); // 将字体大小设置为9px   cellFont.setFontName("宋体"); // 字体应用到当前单元格上   cellNoColorStyle.setFont(cellFont);cellNoColorStyle.setWrapText(true);//设置自动换行// ------------------处理数据/start---------------------//表头int rowNum = 0;if (CollectionUtils.isNotEmpty(titleList)) {for (int i = 0; i < titleList.size(); i++) {int MergedCount = 0;int beginIndex = 0;int endIndex = 0;row = sheet.createRow(rowNum);rowNum++;List<String> titles = titleList.get(i);for (int j = 0; j < titles.size(); j++) {String content = titles.get(j);cell = row.createCell(j);cell.setCellValue("" + content + "");cell.setCellStyle(titleStyle);if (j > 0 && j < titles.size()) {if (content.equals(titles.get(j - 1)) && StringUtils.isNotBlank(content)) {MergedCount++;if (MergedCount == 1) {beginIndex = j - 1;}if (j == titles.size() - 1) {endIndex = j;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), beginIndex, endIndex));}} else if (!content.equals(titles.get(j - 1)) && MergedCount > 0 && j == titles.size() - 1) {endIndex = j - 1;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), beginIndex, endIndex));}}if (i > 0 && i < titleList.size()) {String contentRow = titleList.get(i - 1).get(j);if (i > 0 && i < titleList.size() && contentRow.equals(titles.get(j))) {sheet.addMergedRegion(new CellRangeAddress(row.getRowNum() - 1, row.getRowNum(), j, j));}}}}}//表格数据if (CollectionUtils.isNotEmpty(colorList)) {for (int i = 0; i < dataList.size(); i++) {row = sheet.createRow(rowNum);rowNum++;List<String> rowColorList = colorList.get(i);List<String> rowList = dataList.get(i);for (int j = 0; j < rowList.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + rowList.get(j) + "");XSSFCellStyle cellColorStyle = wb.createCellStyle();String color = rowColorList.get(j);cellColorStyle.setAlignment(HorizontalAlignment.CENTER);cellColorStyle.setVerticalAlignment(VerticalAlignment.CENTER);cellColorStyle.setBorderBottom(BorderStyle.THIN);//下边框  cellColorStyle.setBorderLeft(BorderStyle.THIN);//左边框  cellColorStyle.setBorderRight(BorderStyle.THIN);//右边框  cellColorStyle.setBorderTop(BorderStyle.THIN);//上边框cellColorStyle.setFont(cellFont);cellColorStyle.setWrapText(true);//设置自动换行cellColorStyle.setFillForegroundColor(new XSSFColor(new Color(colorToFloat(color)[0], colorToFloat(color)[1], colorToFloat(color)[2])));cellColorStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);cell.setCellStyle(cellColorStyle);}}} else {for (int i = 0; i < dataList.size(); i++) {row = sheet.createRow(rowNum);rowNum++;List<String> rowList = dataList.get(i);for (int j = 0; j < rowList.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + rowList.get(j) + "");cell.setCellStyle(cellNoColorStyle);}}}if (CollectionUtils.isNotEmpty(dataRatioList)) {rowNum = rowNum + 5;if (CollectionUtils.isNotEmpty(titleList)) {for (int i = 0; i < titleList.size(); i++) {int MergedCount = 0;int beginIndex = 0;int endIndex = 0;row = sheet.createRow(rowNum);rowNum++;List<String> titles = titleList.get(i);for (int j = 0; j < titles.size(); j++) {String content = titles.get(j);cell = row.createCell(j);cell.setCellValue("" + content + "");cell.setCellStyle(titleStyle);if (j > 0 && j < titles.size()) {if (content.equals(titles.get(j - 1)) && StringUtils.isNotBlank(content)) {MergedCount++;if (MergedCount == 1) {beginIndex = j - 1;}if (j == titles.size() - 1) {endIndex = j;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), beginIndex, endIndex));}} else if (!content.equals(titles.get(j - 1)) && MergedCount > 0 && j == titles.size() - 1) {endIndex = j - 1;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), beginIndex, endIndex));}}if (i > 0 && i < titleList.size()) {String contentRow = titleList.get(i - 1).get(j);if (i > 0 && i < titleList.size() && contentRow.equals(titles.get(j))) {sheet.addMergedRegion(new CellRangeAddress(row.getRowNum() - 1, row.getRowNum(), j, j));}}}}}//表格二数据if (CollectionUtils.isNotEmpty(colorRatioList)) {for (int i = 0; i < dataRatioList.size(); i++) {row = sheet.createRow(rowNum);rowNum++;List<String> rowColorList = colorRatioList.get(i);List<String> rowList = dataRatioList.get(i);for (int j = 0; j < rowList.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + rowList.get(j) + "");XSSFCellStyle cellColorStyle = wb.createCellStyle();String color = rowColorList.get(j);cellColorStyle.setAlignment(HorizontalAlignment.CENTER);cellColorStyle.setVerticalAlignment(VerticalAlignment.CENTER);cellColorStyle.setBorderBottom(BorderStyle.THIN);//下边框  cellColorStyle.setBorderLeft(BorderStyle.THIN);//左边框  cellColorStyle.setBorderRight(BorderStyle.THIN);//右边框  cellColorStyle.setBorderTop(BorderStyle.THIN);//上边框cellColorStyle.setFont(cellFont);cellColorStyle.setWrapText(true);//设置自动换行cellColorStyle.setFillForegroundColor(new XSSFColor(new Color(colorToFloat(color)[0], colorToFloat(color)[1], colorToFloat(color)[2])));cellColorStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);cell.setCellStyle(cellColorStyle);}}} else {for (int i = 0; i < dataRatioList.size(); i++) {row = sheet.createRow(rowNum);rowNum++;List<String> rowList = dataRatioList.get(i);for (int j = 0; j < rowList.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + rowList.get(j) + "");cell.setCellStyle(cellNoColorStyle);}}}}//echars数据if (rowNum != 0) {rowNum = rowNum + 5;}if (CollectionUtils.isNotEmpty(echarsList)) {for (int i = 0; i < echarsList.size(); i++) {List<String> echars = echarsList.get(i);if (CollectionUtils.isNotEmpty(echars)) {for (int j = 0; j < echars.size(); j++) {row = sheet.createRow(rowNum);//单元格超32767报错问题修改String content = echars.get(j);if (StringUtils.isNoneBlank(content)) {int max = 32767;int len = content.length();int num = content.length() / max;for (int k = 0; k <= num; k++) {if (k == num) {cell = row.createCell(k);cell.setCellValue("" + content.substring(k * max, len) + "");cell.setCellStyle(echarsStyle);} else {cell = row.createCell(k);cell.setCellValue("" + content.substring(k * max, (k + 1) * max) + "");cell.setCellStyle(echarsStyle);}}}rowNum++;}}}}// ------------------处理数据end--------------------------------------} catch (Exception e) {logger.debug("错误", e);} finally {}return wb;}/*** @Description: 职级图excel* @param <File>* @param <HashMap>* @Author:jlk* @CreateTime:2022-05-24*/@SuppressWarnings("all")public static String writeExcelCustomerPositionClass(File file, HashMap map) throws IOException {//服务器路径+文件名String excelPath = file.toString() + file.separator + map.get("name") + ".xlsx";FileOutputStream fout = new FileOutputStream(excelPath);try {//获取数据源List<Map> dataList = (List<Map>) map.get("dataList");List<Map> titleList = (List<Map>) map.get("titleList");//创建excelXSSFWorkbook wb = new XSSFWorkbook();XSSFRow row = null;XSSFCell cell = null;// 创建新的sheet对象(excel的表单) 并设置sheet名字XSSFSheet sheet = wb.createSheet(map.get("name").toString());sheet.setDefaultRowHeightInPoints(20);sheet.setDefaultColumnWidth(12);XSSFCellStyle titleStyle = getTitleStyle(wb);XSSFCellStyle cellNoColorStyle = getNoColorStyle(wb);// ------------------处理数据/start---------------------//表头int rowNum = 0;List headTitles = new ArrayList();if (CollectionUtils.isNotEmpty(titleList)) {row = sheet.createRow(rowNum);XSSFRow rowSecondLevel = sheet.createRow(rowNum + 1);XSSFCell cellSecondLevel = null;int cellBegin = 0;int cellEnd = 0;for (int i = 0; i < titleList.size(); i++) {Map titles = (Map) titleList.get(i);if ("customerPositionClass.text".equals(titles.get("dataIndex"))) {String title = (String) titles.get("title");cell = row.createCell(i);cell.setCellValue("" + title + "");sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum() + 1, i, i));cell.setCellStyle(titleStyle);cellBegin = cellBegin + 1;headTitles.add(titles.get("dataIndex"));cellSecondLevel = rowSecondLevel.createCell(i);cellSecondLevel.setCellStyle(titleStyle);} else if ("mercerPositionClass.text".equals(titles.get("dataIndex"))) {String title = (String) titles.get("title");cell = row.createCell(i);cell.setCellValue("" + title + "");sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum() + 1, i, i));cell.setCellStyle(titleStyle);cellBegin = cellBegin + 1;headTitles.add(titles.get("dataIndex"));cellSecondLevel = rowSecondLevel.createCell(i);cellSecondLevel.setCellStyle(titleStyle);} else {String title = (String) titles.get("title");cell = row.createCell(cellBegin);cell.setCellValue("" + title + "");cell.setCellStyle(titleStyle);List<Map> childrenList = (List<Map>) titles.get("children");if (CollectionUtils.isNotEmpty(childrenList)) {for (int j = 0; j < childrenList.size(); j++) {String titleSecondLevel = (String) childrenList.get(j).get("title");cell = rowSecondLevel.createCell(cellBegin + j);cell.setCellValue("" + titleSecondLevel + "");cell.setCellStyle(titleStyle);headTitles.add((String) childrenList.get(j).get("dataIndex"));}if (childrenList.size() > 1) {cellEnd = cellBegin + childrenList.size() - 1;sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), cellBegin, cellEnd));cellBegin = cellEnd + 1;} else {cellBegin = cellBegin + 1;}}}}rowNum = rowNum + 2;if (CollectionUtils.isNotEmpty(dataList)) {for (int i = 0; i < dataList.size(); i++) {row = sheet.createRow(rowNum);Map dataMap = dataList.get(i);for (int j = 0; j < headTitles.size(); j++) {String key = headTitles.get(j).toString();String data = (String) dataMap.get(key.substring(0, key.lastIndexOf(".")));if (StringUtils.isBlank(data)) {data = "";}cell = row.createCell(j);cell.setCellValue("" + data + "");cell.setCellStyle(cellNoColorStyle);}rowNum++;}}}// ------------------处理数据end--------------------------------------wb.write(fout);fout.close();} catch (Exception e) {logger.debug("错误", e);} finally {}return excelPath;}public static XSSFCellStyle getTitleStyle(XSSFWorkbook wb) {//----------------表头格样式----------------------------------XSSFCellStyle titleStyle = wb.createCellStyle(); //表格样式titleStyle.setAlignment(HorizontalAlignment.CENTER);titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);titleStyle.setBorderBottom(BorderStyle.THIN);//下边框  titleStyle.setBorderLeft(BorderStyle.THIN);//左边框  titleStyle.setBorderRight(BorderStyle.THIN);//右边框  titleStyle.setBorderTop(BorderStyle.THIN);//上边框titleStyle.setFillForegroundColor(new XSSFColor(new Color(135, 192, 178)));titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);Font ztFont = wb.createFont();ztFont.setItalic(false); // 设置字体为斜体字   //ztFont.setColor(HSSFColor.WHITE.index); // 设置字体颜色-白色  ztFont.setColor(Font.COLOR_NORMAL);ztFont.setFontHeightInPoints((short) 10); // 将字体大小设置为10px   ztFont.setFontName("宋体"); // 字体应用到当前单元格上   ztFont.setBold(true); //加粗titleStyle.setFont(ztFont);//titleStyle.setWrapText(true);//设置自动换行//----------------------------------------------------------return titleStyle;}public static XSSFCellStyle getEcharsStyle(XSSFWorkbook wb) {//----------------Echars格样式----------------------------------XSSFCellStyle echarsStyle = wb.createCellStyle(); //表格样式//echarsStyle.setAlignment(HorizontalAlignment.CENTER);//echarsStyle.setVerticalAlignment(VerticalAlignment.CENTER);Font echarsFont = wb.createFont();echarsFont.setItalic(false); // 设置字体为斜体字   echarsFont.setColor(Font.COLOR_NORMAL); // 设置字体颜色echarsFont.setFontHeightInPoints((short) 10); // 将字体大小设置为10px   echarsFont.setFontName("宋体"); // 字体应用到当前单元格上   echarsFont.setBold(false); //加粗echarsStyle.setFont(echarsFont);//echarsStyle.setWrapText(true);//设置自动换行//----------------------------------------------------------return echarsStyle;}public static XSSFCellStyle getNoColorStyle(XSSFWorkbook wb) {//----------------无色普通格样式----------------------------------XSSFCellStyle cellNoColorStyle = wb.createCellStyle();cellNoColorStyle.setAlignment(HorizontalAlignment.CENTER);cellNoColorStyle.setVerticalAlignment(VerticalAlignment.CENTER);cellNoColorStyle.setBorderBottom(BorderStyle.THIN);//下边框  cellNoColorStyle.setBorderLeft(BorderStyle.THIN);//左边框  cellNoColorStyle.setBorderRight(BorderStyle.THIN);//右边框  cellNoColorStyle.setBorderTop(BorderStyle.THIN);//上边框Font cellFont = wb.createFont();cellFont.setItalic(false); // 设置字体为斜体字   cellFont.setFontHeightInPoints((short) 10); // 将字体大小设置为9px   cellFont.setFontName("宋体"); // 字体应用到当前单元格上   cellNoColorStyle.setFont(cellFont);cellNoColorStyle.setWrapText(true);//设置自动换行//----------------------------------------------------------return cellNoColorStyle;}/*** 初始化 cell 内容长度* cell 原本内容长度限制 32767  现修改为Integer.MAX_VALUE* 未使用*/public static void initCellMaxTextLength() {SpreadsheetVersion excel2007 = SpreadsheetVersion.EXCEL2007;if (Integer.MAX_VALUE != excel2007.getMaxTextLength()) {Field field;try {field = excel2007.getClass().getDeclaredField("_maxTextLength");field.setAccessible(true);field.set(excel2007, Integer.MAX_VALUE);} catch (Exception e) {e.printStackTrace();}}}/*** @Description: excel* @param <File>* @param <HashMap>* @Author:jlk* @CreateTime:2022-05-24*/@SuppressWarnings("all")public static void exportExcelForPreviewCheck(HashMap map, HttpServletRequest request, HttpServletResponse response) throws IOException {response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("方案预览校验表", "UTF-8"));OutputStream outs = response.getOutputStream();try {//获取数据源List<Map> columns = (List<Map>) map.get("columns");List<List<String>> data = (List<List<String>>) map.get("data");//创建excelHSSFWorkbook wb = new HSSFWorkbook();HSSFRow row = null;HSSFCell cell = null;// 创建新的sheet对象(excel的表单) 并设置sheet名字HSSFSheet sheet = wb.createSheet("方案预览校验");sheet.setDefaultRowHeightInPoints(20);sheet.setDefaultColumnWidth(14);HSSFCellStyle cellNoColorStyle = wb.createCellStyle();cellNoColorStyle.setAlignment(HorizontalAlignment.CENTER);cellNoColorStyle.setVerticalAlignment(VerticalAlignment.CENTER);cellNoColorStyle.setBorderBottom(BorderStyle.THIN);//下边框  cellNoColorStyle.setBorderLeft(BorderStyle.THIN);//左边框  cellNoColorStyle.setBorderRight(BorderStyle.THIN);//右边框  cellNoColorStyle.setBorderTop(BorderStyle.THIN);//上边框Font cellFont = wb.createFont();cellFont.setItalic(false); // 设置字体为斜体字   cellFont.setFontHeightInPoints((short) 10); // 将字体大小设置为9px   cellFont.setFontName("宋体"); // 字体应用到当前单元格上   cellNoColorStyle.setFont(cellFont);cellNoColorStyle.setWrapText(true);//设置自动换行// ------------------处理数据/start---------------------//表头int rowNum = 0;if (CollectionUtils.isNotEmpty(columns)) {row = sheet.createRow(rowNum);for (int i = 0; i < columns.size(); i++) {Map column = columns.get(i);cell = row.createCell(i);cell.setCellValue("" + column.get("title") + "");cell.setCellStyle(cellNoColorStyle);}rowNum++;}if (CollectionUtils.isNotEmpty(data)) {for (int i = 0; i < data.size(); i++) {row = sheet.createRow(rowNum);List<String> cellData = data.get(i);for (int j = 0; j < cellData.size(); j++) {cell = row.createCell(j);cell.setCellValue("" + cellData.get(j) + "");cell.setCellStyle(cellNoColorStyle);}rowNum++;}}// ------------------处理数据end--------------------------------------wb.write(outs);outs.close();} catch (Exception e) {e.printStackTrace();} }/*** @Description: 下载PPT* @param <map>* @param <HttpServletResponse>* @Author:jlk* @CreateTime:2022-05-24* @throws IOException*/@SuppressWarnings("all")public static void downloadSchemeAnalysesPPT(String customerName, List<SchemeAnalysis> schemeAnalyses, HttpServletRequest request,HttpServletResponse response) throws IOException {String path = request.getSession().getServletContext().getRealPath("upload");String fileName = UUID.randomUUID().toString();File file = new File(path + File.separator + fileName);if (file.mkdirs()) {logger.debug("生成文件夹成功", file.toString());}response.reset();response.setContentType("application/zip");response.setCharacterEncoding("utf-8");response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(customerName + "_分析图表_" + TimestampTool.getDate(new Date()), "UTF-8"));OutputStream outs = response.getOutputStream();//创建pptXMLSlideShow ppt = new XMLSlideShow();File pptPath = new File(file + File.separator + customerName + "_分析图表_" + TimestampTool.getDate(new Date()) + ".pptx");Map<Integer, String> dataMap = new HashMap<>();FileOutputStream pptbaos = new FileOutputStream(pptPath);//创建excelXSSFWorkbook wb = new XSSFWorkbook();File excelPath = new File(file + File.separator + customerName + "_分析图表_" + TimestampTool.getDate(new Date()) + ".xlsx");FileOutputStream excelbaos = new FileOutputStream(excelPath);boolean isppt = false;boolean isexcel = false;try {for (int j = 0; j < schemeAnalyses.size(); j++) {String base64 = schemeAnalyses.get(j).getAnalysisImage();String data = schemeAnalyses.get(j).getAnalysisData();String name = schemeAnalyses.get(j).getAnalysisTopicName();if (StringUtils.isNotBlank(base64)) {XSLFSlide slide = ppt.createSlide();XSLFTextBox shape1 = slide.createTextBox();Rectangle anchor = new Rectangle(30, 30, 300, 50);shape1.setAnchor(anchor);XSLFTextParagraph p1 = shape1.addNewTextParagraph();XSLFTextRun r1 = p1.addNewTextRun();r1.setFontSize(14.00);r1.setFontColor(Color.black);//shape1.setFillColor(Color.red);r1.setText(name);// 图片文件String imgPathName = file.toString() + File.separator + schemeAnalyses.get(j).getAnalysisTopicName();String imgPath = Base64Util.generateImage(base64, imgPathName);File image = new File(imgPath);//测试用本地图片//File image = new File("E://plief.jpg");// 图片文件输入流FileInputStream imageFis = new FileInputStream(image);// 获取图片大小int len = (int) image.length();// 创建一个字节数组,数组大小与图片文件大小一致byte[] imageData = new byte[len];// 将图片数据读进字节数组中int pictureData = imageFis.read(imageData);// 将图片添加到PPT中XSLFPictureData pd = ppt.addPicture(imageData, PictureType.PNG);// 将图片放到指定的幻灯片中XSLFPictureShape pic = slide.createPicture(pd);// 设置图片框的放置的位置和大小pic.setAnchor(new Rectangle2D.Double(100, 160, 520, 200));isppt = true;imageFis.close();}if (StringUtils.isNotBlank(data)) {JSONObject object = JSONObject.parseObject(data);writeExcel(object, wb);isexcel = true;}}ppt.write(pptbaos);wb.write(excelbaos);List<File> fileList = new ArrayList<>();if (isppt)fileList.add(pptPath);if (isexcel)fileList.add(excelPath);ZipUtils.toZip(fileList, outs);} catch (Exception e) {logger.debug("错误", e);} finally {pptbaos.flush();pptbaos.close();excelbaos.flush();excelbaos.close();outs.flush();outs.close();FileUtilsExt.delFile(file.toString());}}}

zip 工具类

package com.sapit.compensation.common.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;/*** ZipUtils* @author    季连科* @date     2022年5月23日 下午7:16:08* @version v1.0*/
public class ZipUtils {private static final int  BUFFER_SIZE = 2 * 1024;/*** 压缩成ZIP 方法1* @param srcDir 压缩文件夹路径 * @param out    压缩文件输出流* @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; *                             false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)* @throws RuntimeException 压缩失败会抛出运行时异常*/public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)throws RuntimeException{long start = System.currentTimeMillis();ZipOutputStream zos = null ;try {zos = new ZipOutputStream(out);File sourceFile = new File(srcDir);compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);long end = System.currentTimeMillis();System.out.println("压缩完成,耗时:" + (end - start) +" ms");} catch (Exception e) {throw new RuntimeException("zip error from ZipUtils",e);}finally{if(zos != null){try {zos.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 压缩成ZIP 方法2* @param srcFiles 需要压缩的文件列表* @param out          压缩文件输出流* @throws RuntimeException 压缩失败会抛出运行时异常*/public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {long start = System.currentTimeMillis();ZipOutputStream zos = null ;try {zos = new ZipOutputStream(out);for (File srcFile : srcFiles) {byte[] buf = new byte[BUFFER_SIZE];zos.putNextEntry(new ZipEntry(srcFile.getName()));int len;FileInputStream in = new FileInputStream(srcFile);while ((len = in.read(buf)) != -1){zos.write(buf, 0, len);}zos.closeEntry();in.close();}long end = System.currentTimeMillis();System.out.println("压缩完成,耗时:" + (end - start) +" ms");} catch (Exception e) {throw new RuntimeException("zip error from ZipUtils",e);}finally{if(zos != null){try {zos.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 递归压缩方法* @param sourceFile 源文件* @param zos      zip输出流* @param name        压缩后的名称* @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; *                           false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)* @throws Exception*/private static void compress(File sourceFile, ZipOutputStream zos, String name,boolean KeepDirStructure) throws Exception{byte[] buf = new byte[BUFFER_SIZE];if(sourceFile.isFile()){// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字zos.putNextEntry(new ZipEntry(name));// copy文件到zip输出流中int len;FileInputStream in = new FileInputStream(sourceFile);while ((len = in.read(buf)) != -1){zos.write(buf, 0, len);}// Complete the entryzos.closeEntry();in.close();} else {File[] listFiles = sourceFile.listFiles();if(listFiles == null || listFiles.length == 0){// 需要保留原来的文件结构时,需要对空文件夹进行处理if(KeepDirStructure){// 空文件夹的处理zos.putNextEntry(new ZipEntry(name + "/"));// 没有文件,不需要文件的copyzos.closeEntry();}}else {for (File file : listFiles) {// 判断是否需要保留原来的文件结构if (KeepDirStructure) {// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了compress(file, zos, name + "/" + file.getName(),KeepDirStructure);} else {compress(file, zos, file.getName(),KeepDirStructure);}}}}}public static void main(String[] args) throws Exception {/** 测试压缩方法1  */FileOutputStream fos1 = new FileOutputStream(new File("c:/mytest01.zip"));ZipUtils.toZip("D:/log", fos1,true);/** 测试压缩方法2  */List<File> fileList = new ArrayList<>();fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));ZipUtils.toZip(fileList, fos2);}public static void zipFile(File inputFile, ZipOutputStream zipoutputStream) {FileInputStream fis = null;BufferedInputStream bis = null;try {if (inputFile.exists()) { // 判断文件是否存在if (inputFile.isFile()) {  // 如果是文件// 创建输入流读取文件fis = new FileInputStream(inputFile);bis = new BufferedInputStream(fis);// 将文件写入zip压缩包内ZipEntry zip =new ZipEntry(inputFile.getParentFile().getName() + File.separator + inputFile.getName()); //获取文件名zipoutputStream.putNextEntry(zip);// 进行写入文件byte[] bytes = new byte[1024];long fileLength = 0;while (fileLength < inputFile.length()) {int count = bis.read(bytes, 0, 1024);fileLength += count;zipoutputStream.write(bytes, 0, count);}// 关闭输入输出流if (bis != null) {bis.close();}if (fis != null) {fis.close();}} else {  // 如果是文件夹,则使用穷举的方法获取文件,写入ziptry {zipoutputStream.putNextEntry(new ZipEntry(inputFile.getName() + File.separator));File[] files = inputFile.listFiles();for (int i = 0; i < files.length; i++) {zipFile(files[i], zipoutputStream);}} catch (Exception e) {e.printStackTrace();}}}} catch (Exception e) {e.printStackTrace();} finally {try {if (bis != null) {bis.close();}if (fis != null) {fis.close();}} catch (IOException e) {e.printStackTrace();}}}
}

base64转码工具类

package com.sapit.compensation.common.util;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;import org.apache.commons.lang3.StringUtils;/*** <p>文件名称: Base64Util.java </p> * <p>类型描述: [base64处理工具] </p>* <p>创建时间: 2022年5月23日 </p>* @author jlk* @version V1.0*/
public class Base64Util {/*** <p>功能描述: [解码] </p>* @Title decode* @param str base64编码* @return byte[]*/public static byte[] decode(String str) {return Base64.getDecoder().decode(str);}/*** <p>功能描述: [编码] </p>* @Title encode* @param bytes 需要转换的bytes.* @return String*/public static String encode(byte[] bytes) {return Base64.getEncoder().encodeToString(bytes);}/*** <p>功能描述: [将base64转成文件] </p>* @Title toFile* @param str* @param filePath* @return boolean*/public static boolean toFile(String str, String filePath) {if (StringUtils.isEmpty(str)||StringUtils.isEmpty(filePath)) {return false;}OutputStream out=null;try {// Base64解码byte[] b = decode(str);for (int i = 0; i < b.length; ++i) {// 调整异常数据if (b[i] < 0) {b[i] += 256;}}// 生成jpeg图片File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}out = new FileOutputStream(file);out.write(b);out.flush();return true;} catch (Exception e) {return false;}finally {if(out!=null) {try {out.close();} catch (IOException e) {}}}}/*** @Description: 将base64编码字符串转换为图片* @Author:* @CreateTime:* @param file base64编码字符串* @param path 图片路径-具体到文件* @return* @throws IOException */public static String generateImage(String file, String path) throws IOException {// 解密OutputStream out = null;try {// 项目绝对路径// 图片分类路径+图片名+图片后缀String imgClassPath = path.concat(".jpg");// 解密Base64.Decoder decoder = Base64.getDecoder();// 去掉base64前缀 data:image/jpeg;base64,file = file.substring(file.indexOf(",", 1) + 1, file.length());byte[] b = decoder.decode(file);// 处理数据for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {b[i] += 256;}}// 保存图片out = new FileOutputStream(imgClassPath);out.write(b);// 返回图片的相对路径 = 图片分类路径+图片名+图片后缀return imgClassPath;} catch (IOException e) {return null;}finally {out.flush();out.close();}}}

文件工具类

package com.sapit.compensation.common.util;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.google.common.collect.Lists;/*** 文件操作工具类 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能** @author aoyuan* @version 2015-3-16*/
public class FileUtilsExt extends org.apache.commons.io.FileUtils {private static final String HTML = "html";private static final String HTM = "htm";private static final String SHTML = "shtml";private static final String APK = "apk";private static final String SIS = "sis";private static final String SISX = "sisx";private static final String EXE = "exe";private static final String MSI = "msi";private static final String CSS = "css";private static final String XML = "xml";private static final String GIF = "gif";private static final String JPEG = "jpeg";private static final String JPG = "jpg";private static final String JS = "js";private static final String ATOM = "atom";private static final String RSS = "rss";private static final String MML = "mml";private static final String TXT = "txt";private static final String JAD = "jad";private static final String WML = "wml";private static final String HTC = "htc";private static final String PNG = "png";private static final String TIF = "tif";private static final String TIFF = "tiff";private static final String WBMP = "wbmp";private static final String ICO = "ico";private static final String JNG = "jng";private static final String BMP = "bmp";private static final String SVG = "svg";private static final String JAR = "jar";private static final String VAR = "var";private static final String EAR = "ear";private static final String DOC = "doc";private static final String PDF = "pdf";private static final String RTF = "rtf";private static final String XLS = "xls";private static final String PPT = "ppt";private static final String SEVEN_Z = "7z";private static final String RAR = "rar";private static final String SWF = "swf";private static final String RPM = "rpm";private static final String DER = "der";private static final String PEM = "pem";private static final String CRT = "crt";private static final String XHTML = "xhtml";private static final String ZIP = "zip";private static final String MID = "mid";private static final String MIDI = "midi";private static final String KAR = "kar";private static final String MP3 = "mp3";private static final String OGG = "ogg";private static final String M4A = "m4a";private static final String RA = "ra";private static final String THREE_GPP = "3gpp";private static final String THREE_GP = "3gp";private static final String MP4 = "mp4";private static final String MPEG = "mpeg";private static final String MPG = "mpg";private static final String MOV = "mov";private static final String FLV = "flv";private static final String M4V = "m4v";private static final String MNG = "pem";private static final String ASX = "asx";private static final String ASF = "asf";private static final String WMV = "wmv";private static final String AVI = "avi";private static Logger logger = LoggerFactory.getLogger(com.sapit.compensation.common.util.FileUtilsExt.class);/*** 复制单个文件,如果目标文件存在,则不覆盖** @param srcFileName  待复制的文件名* @param descFileName 目标文件名* @return 如果复制成功,则返回true,否则返回false*/public static boolean copyFile(String srcFileName, String descFileName) {return com.sapit.compensation.common.util.FileUtilsExt.copyFileCover(srcFileName, descFileName, false);}/*** 复制单个文件** @param srcFileName  待复制的文件名* @param descFileName 目标文件名* @param coverlay     如果目标文件已存在,是否覆盖* @return 如果复制成功,则返回true,否则返回false*/public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) {File srcFile = new File(srcFileName);// 判断源文件是否存在if (!srcFile.exists()) {logger.debug("复制文件失败,源文件 {} 不存在!", srcFileName);return false;}// 判断源文件是否是合法的文件else if (!srcFile.isFile()) {logger.debug("复制文件失败,{} 不是一个文件!", srcFileName);return false;}File descFile = new File(descFileName);// 判断目标文件是否存在if (descFile.exists()) {// 如果目标文件存在,并且允许覆盖if (coverlay) {logger.debug("目标文件已存在,准备删除!");if (!com.sapit.compensation.common.util.FileUtilsExt.delFile(descFileName)) {logger.debug("删除目标文件 {} 失败!", descFileName);return false;}} else {logger.debug("复制文件失败,目标文件{} 已存在!", descFileName);return false;}} else {if (!descFile.getParentFile().exists()) {// 如果目标文件所在的目录不存在,则创建目录logger.debug("目标文件所在的目录不存在,创建目录!");// 创建目标文件所在的目录if (!descFile.getParentFile().mkdirs()) {logger.debug("创建目标文件所在的目录失败!");return false;}}}// 准备复制文件// 读取的位数int readByte = 0;InputStream ins = null;OutputStream outs = null;try {// 打开源文件ins = new FileInputStream(srcFile);// 打开目标文件的输出流outs = new FileOutputStream(descFile);byte[] buf = new byte[1024];// 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕while ((readByte = ins.read(buf)) != -1) {// 将读取的字节流写入到输出流outs.write(buf, 0, readByte);}logger.info("复制单个文件{} 到 {} 成功!", srcFileName, descFileName);return true;} catch (Exception e) {logger.info("复制文件失败:{}", e.getMessage());return false;} finally {// 关闭输入输出流,首先关闭输出流,然后再关闭输入流if (outs != null) {try {outs.close();} catch (IOException oute) {logger.info(oute.getMessage());}}if (ins != null) {try {ins.close();} catch (IOException ine) {logger.info(ine.getMessage());}}}}/*** 复制整个目录的内容,如果目标目录存在,则不覆盖** @param srcDirName  源目录名* @param descDirName 目标目录名* @return 如果复制成功返回true,否则返回false*/public static boolean copyDirectory(String srcDirName, String descDirName) {return com.sapit.compensation.common.util.FileUtilsExt.copyDirectoryCover(srcDirName, descDirName, false);}/*** 复制整个目录的内容** @param srcDirName  源目录名* @param descDirName 目标目录名* @param coverlay    如果目标目录存在,是否覆盖* @return 如果复制成功返回true,否则返回false*/public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) {File srcDir = new File(srcDirName);// 判断源目录是否存在if (!srcDir.exists()) {logger.debug("复制目录失败,源目录 {} 不存在!", srcDirName);return false;}// 判断源目录是否是目录else if (!srcDir.isDirectory()) {logger.debug("复制目录失败,{} 不是一个目录!", srcDirName);return false;}// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符String descDirNames = descDirName;if (!descDirNames.endsWith(File.separator)) {descDirNames = descDirNames + File.separator;}File descDir = new File(descDirNames);// 如果目标文件夹存在if (descDir.exists()) {if (coverlay) {// 允许覆盖目标目录logger.debug("目标目录已存在,准备删除!");if (!com.sapit.compensation.common.util.FileUtilsExt.delFile(descDirNames)) {logger.debug("删除目录 {} 失败!", descDirNames);return false;}} else {logger.debug("目标目录复制失败,目标目录 {} 已存在!", descDirNames);return false;}} else {// 创建目标目录logger.debug("目标目录不存在,准备创建!");if (!descDir.mkdirs()) {logger.debug("创建目标目录失败!");return false;}}boolean flag = true;// 列出源目录下的所有文件名和子目录名File[] files = srcDir.listFiles();for (int i = 0; i < files.length; i++) {// 如果是一个单个文件,则直接复制if (files[i].isFile()) {flag = com.sapit.compensation.common.util.FileUtilsExt.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName());// 如果拷贝文件失败,则退出循环if (!flag) {break;}}// 如果是子目录,则继续复制目录if (files[i].isDirectory()) {flag = com.sapit.compensation.common.util.FileUtilsExt.copyDirectory(files[i].getAbsolutePath(), descDirName + files[i].getName());// 如果拷贝目录失败,则退出循环if (!flag) {break;}}}if (!flag) {logger.debug("复制目录 {} 到 {} 失败!", srcDirName, descDirName);return false;}logger.debug("复制目录 {} 到 {} 成功!", srcDirName, descDirName);return true;}/*** 删除文件,可以删除单个文件或文件夹** @param fileName 被删除的文件名* @return 如果删除成功,则返回true,否是返回false*/public static boolean delFile(String fileName) {File file = new File(fileName);if (!file.exists()) {logger.debug("{} 文件不存在!", fileName);return true;} else {if (file.isFile()) {return com.sapit.compensation.common.util.FileUtilsExt.deleteFile(fileName);} else {return com.sapit.compensation.common.util.FileUtilsExt.deleteDirectory(fileName);}}}/*** 删除单个文件** @param fileName 被删除的文件名* @return 如果删除成功,则返回true,否则返回false*/public static boolean deleteFile(String fileName) {File file = new File(fileName);if (file.exists() && file.isFile()) {if (file.delete()) {logger.debug("删除文件 {} 成功!", fileName);return true;} else {logger.debug("删除文件 {} 失败!", fileName);return false;}} else {logger.debug("{} 文件不存在!", fileName);return true;}}/*** 删除目录及目录下的文件** @param dirName 被删除的目录所在的文件路径* @return 如果目录删除成功,则返回true,否则返回false*/public static boolean deleteDirectory(String dirName) {String dirNames = dirName;if (!dirNames.endsWith(File.separator)) {dirNames = dirNames + File.separator;}File dirFile = new File(dirNames);if (!dirFile.exists() || !dirFile.isDirectory()) {logger.debug("{} 目录不存在!", dirNames);return true;}boolean flag = true;// 列出全部文件及子目录File[] files = dirFile.listFiles();for (int i = 0; i < files.length; i++) {// 删除子文件if (files[i].isFile()) {flag = com.sapit.compensation.common.util.FileUtilsExt.deleteFile(files[i].getAbsolutePath());// 如果删除文件失败,则退出循环if (!flag) {break;}}// 删除子目录else if (files[i].isDirectory()) {flag = com.sapit.compensation.common.util.FileUtilsExt.deleteDirectory(files[i].getAbsolutePath());// 如果删除子目录失败,则退出循环if (!flag) {break;}}}if (!flag) {logger.debug("删除目录失败!");return false;}// 删除当前目录if (dirFile.delete()) {logger.debug("删除目录 {} 成功!", dirName);return true;} else {logger.debug("删除目录 {} 失败!", dirName);return false;}}/*** 创建单个文件** @param descFileName 文件名,包含路径* @return 如果创建成功,则返回true,否则返回false*/public static boolean createFile(String descFileName) {File file = new File(descFileName);if (file.exists()) {logger.debug("文件{} 已存在!", descFileName);return false;}if (descFileName.endsWith(File.separator)) {logger.debug("{} 为目录,不能创建目录!", descFileName);return false;}if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {// 如果文件所在的目录不存在,则创建目录logger.debug("创建文件所在的目录失败!");return false;}// 创建文件try {if (file.createNewFile()) {logger.debug("{} 文件创建成功!", descFileName);return true;} else {logger.info("{} 文件创建失败!", descFileName);return false;}} catch (Exception e) {logger.info("{} 文件创建失败!", descFileName);return false;}}/*** 创建目录** @param descDirName 目录名,包含路径* @return 如果创建成功,则返回true,否则返回false*/public static boolean createDirectory(String descDirName) {String descDirNames = descDirName;if (!descDirNames.endsWith(File.separator)) {descDirNames = descDirNames + File.separator;}File descDir = new File(descDirNames);if (descDir.exists()) {logger.debug("目录 {} 已存在!", descDirNames);return false;}// 创建目录if (descDir.mkdirs()) {logger.debug("目录  {} 创建成功!", descDirNames);return true;} else {logger.debug("目录  {} 创建失败!", descDirNames);return false;}}/*** 写入文件** @param fileName* @param content* @param append*/public static void writeToFile(String fileName, String content, boolean append) {try {org.apache.commons.io.FileUtils.write(new File(fileName), content, "utf-8", append);logger.debug("文件  {} 写入成功!", fileName);} catch (IOException e) {logger.info("文件  {} 写入失败!  {}", fileName, e.getMessage());}}/*** 写入文件** @param fileName* @param content* @param encoding* @param append*/public static void writeToFile(String fileName, String content, String encoding, boolean append) {try {org.apache.commons.io.FileUtils.write(new File(fileName), content, encoding, append);logger.debug("文件  {} 写入成功!", fileName);} catch (IOException e) {logger.info("文件  {} 写入失败! {}", fileName, e.getMessage());}}/*** 压缩文件或目录** @param srcDirName   压缩的根目录* @param fileName     根目录下的待压缩的文件名或文件夹名,其中*或""表示跟目录下的全部文件* @param descFileName 目标zip文件*/public static void zipFiles(String srcDirName, String fileName, String descFileName) {// 判断目录是否存在if (srcDirName == null) {logger.debug("文件压缩失败,目录  {} 不存在! ", srcDirName);return;}File fileDir = new File(srcDirName);if (!fileDir.exists() || !fileDir.isDirectory()) {logger.debug("文件压缩失败,目录  {} 不存在! ", srcDirName);return;}String dirPath = fileDir.getAbsolutePath();File descFile = new File(descFileName);FileOutputStream fos = null;ZipOutputStream zouts = null;try {fos = new FileOutputStream(descFile);zouts = new ZipOutputStream(fos);if ("*".equals(fileName) || "".equals(fileName)) {com.sapit.compensation.common.util.FileUtilsExt.zipDirectoryToZipFile(dirPath, fileDir, zouts);} else {File file = new File(fileDir, fileName);if (file.isFile()) {com.sapit.compensation.common.util.FileUtilsExt.zipFilesToZipFile(dirPath, file, zouts);} else {com.sapit.compensation.common.util.FileUtilsExt.zipDirectoryToZipFile(dirPath, file, zouts);}}logger.debug("{} 文件压缩成功!", descFileName);} catch (Exception e) {logger.info("文件压缩失败: {}", e.getMessage());} finally {IOUtils.closeQuietly(fos);IOUtils.closeQuietly(zouts);}}/*** 将目录压缩到ZIP输出流** @param dirPath 目录路径* @param fileDir 文件信息* @param zouts   输出流*/public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {if (fileDir.isDirectory()) {File[] files = fileDir.listFiles();// 空的文件夹if (files.length == 0) {// 目录信息ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));try {zouts.putNextEntry(entry);zouts.closeEntry();} catch (Exception e) {logger.info("异常", e);}return;}for (int i = 0; i < files.length; i++) {if (files[i].isFile()) {// 如果是文件,则调用文件压缩方法com.sapit.compensation.common.util.FileUtilsExt.zipFilesToZipFile(dirPath, files[i], zouts);} else {// 如果是目录,则递归调用com.sapit.compensation.common.util.FileUtilsExt.zipDirectoryToZipFile(dirPath, files[i], zouts);}}}}/*** 将文件压缩到ZIP输出流** @param dirPath 目录路径* @param file    文件* @param zouts   输出流*/public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {FileInputStream fin = null;ZipEntry entry;// 创建复制缓冲区byte[] buf = new byte[4096];int readByte;if (file.isFile()) {try {// 创建一个文件输入流fin = new FileInputStream(file);// 创建一个ZipEntryentry = new ZipEntry(getEntryName(dirPath, file));// 存储信息到压缩文件zouts.putNextEntry(entry);// 复制字节到压缩文件while ((readByte = fin.read(buf)) != -1) {zouts.write(buf, 0, readByte);}zouts.closeEntry();fin.close();logger.info("添加文件{} 到zip文件中!", file.getAbsolutePath());} catch (Exception e) {logger.info("异常", e);} finally {IOUtils.closeQuietly(fin);}}}/*** 获取待压缩文件在ZIP文件中entry的名字,即相对于跟目录的相对路径名** @param dirPath 目录名* @param file    entry文件名* @return*/private static String getEntryName(String dirPath, File file) {String dirPaths = dirPath;if (!dirPaths.endsWith(File.separator)) {dirPaths = dirPaths + File.separator;}String filePath = file.getAbsolutePath();// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储if (file.isDirectory()) {filePath += "/";}int index = filePath.indexOf(dirPaths);return filePath.substring(index + dirPaths.length());}/*** 根据“文件名的后缀”获取文件内容类型(而非根据File.getContentType()读取的文件类型)** @param returnFileName 带验证的文件名* @return 返回文件类型*/public static String getContentType(String returnFileName) {String contentType = "application/octet-stream";if (returnFileName.lastIndexOf('.') < 0) {return contentType;}returnFileName = returnFileName.toLowerCase();returnFileName = returnFileName.substring(returnFileName.lastIndexOf('.') + 1);if (returnFileName.equals(HTML) || returnFileName.equals(HTM) || returnFileName.equals(SHTML)) {contentType = "text/html";} else if (returnFileName.equals(APK)) {contentType = "application/vnd.android.package-archive";} else if (returnFileName.equals(SIS) || returnFileName.equals(SISX)) {contentType = "application/vnd.symbian.install";} else if (returnFileName.equals(EXE) || returnFileName.equals(MSI)) {contentType = "application/x-msdownload";} else if (returnFileName.equals(CSS)) {contentType = "text/css";} else if (returnFileName.equals(XML)) {contentType = "text/xml";} else if (returnFileName.equals(GIF)) {contentType = "image/gif";} else if (returnFileName.equals(JPEG) || returnFileName.equals(JPG)) {contentType = "image/jpeg";} else if (returnFileName.equals(JS)) {contentType = "application/x-javascript";} else if (returnFileName.equals(ATOM)) {contentType = "application/atom+xml";} else if (returnFileName.equals(RSS)) {contentType = "application/rss+xml";} else if (returnFileName.equals(MML)) {contentType = "text/mathml";} else if (returnFileName.equals(TXT)) {contentType = "text/plain";} else if (returnFileName.equals(JAD)) {contentType = "text/vnd.sun.j2me.app-descriptor";} else if (returnFileName.equals(WML)) {contentType = "text/vnd.wap.wml";} else if (returnFileName.equals(HTC)) {contentType = "text/x-component";} else if (returnFileName.equals(PNG)) {contentType = "image/png";} else if (returnFileName.equals(TIF) || returnFileName.equals(TIFF)) {contentType = "image/tiff";} else if (returnFileName.equals(WBMP)) {contentType = "image/vnd.wap.wbmp";} else if (returnFileName.equals(ICO)) {contentType = "image/x-icon";} else if (returnFileName.equals(JNG)) {contentType = "image/x-jng";} else if (returnFileName.equals(BMP)) {contentType = "image/x-ms-bmp";} else if (returnFileName.equals(SVG)) {contentType = "image/svg+xml";} else if (returnFileName.equals(JAR) || returnFileName.equals(VAR) || returnFileName.equals(EAR)) {contentType = "application/java-archive";} else if (returnFileName.equals(DOC)) {contentType = "application/msword";} else if (returnFileName.equals(PDF)) {contentType = "application/pdf";} else if (returnFileName.equals(RTF)) {contentType = "application/rtf";} else if (returnFileName.equals(XLS)) {contentType = "application/vnd.ms-excel";} else if (returnFileName.equals(PPT)) {contentType = "application/vnd.ms-powerpoint";} else if (returnFileName.equals(SEVEN_Z)) {contentType = "application/x-7z-compressed";} else if (returnFileName.equals(RAR)) {contentType = "application/x-rar-compressed";} else if (returnFileName.equals(SWF)) {contentType = "application/x-shockwave-flash";} else if (returnFileName.equals(RPM)) {contentType = "application/x-redhat-package-manager";} else if (returnFileName.equals(DER) || returnFileName.equals(PEM) || returnFileName.equals(CRT)) {contentType = "application/x-x509-ca-cert";} else if (returnFileName.equals(XHTML)) {contentType = "application/xhtml+xml";} else if (returnFileName.equals(ZIP)) {contentType = "application/zip";} else if (returnFileName.equals(MID) || returnFileName.equals(MIDI) || returnFileName.equals(KAR)) {contentType = "audio/midi";} else if (returnFileName.equals(MP3)) {contentType = "audio/mpeg";} else if (returnFileName.equals(OGG)) {contentType = "audio/ogg";} else if (returnFileName.equals(M4A)) {contentType = "audio/x-m4a";} else if (returnFileName.equals(RA)) {contentType = "audio/x-realaudio";} else if (returnFileName.equals(THREE_GPP) || returnFileName.equals(THREE_GP)) {contentType = "video/3gpp";} else if (returnFileName.equals(MP4)) {contentType = "video/mp4";} else if (returnFileName.equals(MPEG) || returnFileName.equals(MPG)) {contentType = "video/mpeg";} else if (returnFileName.equals(MOV)) {contentType = "video/quicktime";} else if (returnFileName.equals(FLV)) {contentType = "video/x-flv";} else if (returnFileName.equals(M4V)) {contentType = "video/x-m4v";} else if (returnFileName.equals(MNG)) {contentType = "video/x-mng";} else if (returnFileName.equals(ASX) || returnFileName.equals(ASF)) {contentType = "video/x-ms-asf";} else if (returnFileName.equals(WMV)) {contentType = "video/x-ms-wmv";} else if (returnFileName.equals(AVI)) {contentType = "video/x-msvideo";}return contentType;}/*** 修正路径,将 \\ 或 / 等替换为 File.separator** @param path 待修正的路径* @return 修正后的路径*/public static String path(String path) {String p = org.apache.commons.lang3.StringUtils.replace(path, "\\", "/");p = org.apache.commons.lang3.StringUtils.join(org.apache.commons.lang3.StringUtils.split(p, "/"), "/");if (!org.apache.commons.lang3.StringUtils.startsWithAny(p, "/") && org.apache.commons.lang3.StringUtils.startsWithAny(path, "\\", "/")) {p += "/";}if (!org.apache.commons.lang3.StringUtils.endsWithAny(p, "/") && org.apache.commons.lang3.StringUtils.endsWithAny(path, "\\", "/")) {p = p + "/";}if (path != null && path.startsWith("/")) {p = "/" + p; // linux下路径}return p;}/*** 获目录下的文件列表** @param dir        搜索目录* @param searchDirs 是否是搜索目录* @return 文件列表*/public static List<String> findChildrenList(File dir, boolean searchDirs) {List<String> files = Lists.newArrayList();for (String subFiles : dir.list()) {File file = new File(dir, subFiles);if (((searchDirs) && (file.isDirectory())) || ((!searchDirs) && (!file.isDirectory()))) {files.add(file.getName());}}return files;}/*** 获取文件扩展名(返回小写)** @param fileName 文件名* @return 例如:test.jpg 返回: jpg*/public static String getFileExtension(String fileName) {if ((fileName == null) || (fileName.lastIndexOf('.') == -1) || (fileName.lastIndexOf('.') == fileName.length() - 1)) {return null;}return org.apache.commons.lang3.StringUtils.lowerCase(fileName.substring(fileName.lastIndexOf('.') + 1));}/*** 获取文件名,不包含扩展名** @param fileName 文件名* @return 例如:d:\files\test.jpg 返回:d:\files\test*/public static String getFileNameWithoutExtension(String fileName) {if ((fileName == null) || (fileName.lastIndexOf('.') == -1)) {return null;}return fileName.substring(0, fileName.lastIndexOf('.'));}/*** <p>功能描述: [自动创建多层目录] </p>* @Title mkdirs* @param destPath*/public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}
}

时间戳工具类


package com.sapit.compensation.common.util;import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;public final class TimestampTool {private static String formatter = "yyyy-MM-dd";private static Logger logger = LoggerFactory.getLogger(TimestampTool.class);private TimestampTool() {throw new IllegalStateException("Utility class");}// 当前时间public static Timestamp crunttime() {return new Timestamp(System.currentTimeMillis());}// 获取当前时间的字符串 2006-07-07public static String getCurrentDate() {Timestamp d = crunttime();return d.toString().substring(0, 10);}// 获取当前时间的字符串 2006-07-07 22:10:10public static String getCurrentDateTime() {Timestamp d = crunttime();return d.toString().substring(0, 19);}// 获取给定时间的字符串,只有日期 2006-07-07public static String getStrDate(Timestamp t) {return t.toString().substring(0, 10);}// 获取给定时间的字符串,只有日期 20060707public static String getStringDate() {Timestamp t = crunttime();return t.toString().substring(0, 10).replace("-", "");}// 获取给定时间的字符串 2006-07-07 22:10:10public static String getStrDateTime(Timestamp t) {return t.toString().substring(0, 19);}// 获取当前日期之前的日期字符串 如 2007-04-15 前5月 就是 2006-11-15public static String getPreviousMonth(int month) {Calendar cal1 = Calendar.getInstance();cal1.setTime(new Date());cal1.add(Calendar.MONTH, -month);SimpleDateFormat format = new SimpleDateFormat(formatter);return format.format(cal1.getTime());}public static String getPreviousMonth(int month, String format) {Calendar cal1 = Calendar.getInstance();cal1.setTime(new Date());cal1.add(Calendar.MONTH, -month);SimpleDateFormat formatter = new SimpleDateFormat(format);return formatter.format(cal1.getTime());}public static String getPreviousMonth(Date date, int month) {Calendar cal1 = Calendar.getInstance();cal1.setTime(date);cal1.add(Calendar.MONTH, -month);SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return formatter.format(cal1.getTime());}/*** 日期月份加减** @param date  Date* @param month 正数:向前推xxx个月,负数:向后推xxx个月* @return Date* @author YJH*/public static Date getPreviousMonthReturnDate(Date date, int month) {Calendar cal1 = Calendar.getInstance();cal1.setTime(date);cal1.add(Calendar.MONTH, -month);return cal1.getTime();}public static String getPreviousMonth(Date date, int month, String format) {Calendar cal1 = Calendar.getInstance();cal1.setTime(date);cal1.add(Calendar.MONTH, -month);SimpleDateFormat formatter = new SimpleDateFormat(format);return formatter.format(cal1.getTime());}// 获取当前日期之后的日期字符串 如 2007-04-15 后一天 就是 2007-04-16public static String getNextDay(int day) {Calendar cal1 = Calendar.getInstance();cal1.setTime(new Date());cal1.add(Calendar.DAY_OF_MONTH, day);SimpleDateFormat format = new SimpleDateFormat(formatter);return format.format(cal1.getTime());}public static Date getNextHour(int hour) {Calendar cal1 = Calendar.getInstance();cal1.setTime(new Date());cal1.add(Calendar.HOUR_OF_DAY, hour);return cal1.getTime();}public static Date getNextHour(Date date, int hour) {Calendar cal1 = Calendar.getInstance();cal1.setTime(date);cal1.add(Calendar.HOUR_OF_DAY, hour);return cal1.getTime();}public static Date getNextMinute(int minute) {Calendar cal1 = Calendar.getInstance();cal1.setTime(new Date());cal1.add(Calendar.MINUTE, minute);return cal1.getTime();}// 获取指定日期之后的日期字符串 如 2007-04-15 后一天 就是 2007-04-16public static String getNextDay(String strDate, int day) {Calendar c = Calendar.getInstance();String[] string = strDate.trim().split("-");int one = Integer.parseInt(string[0]) - 1900;int two = Integer.parseInt(string[1]) - 1;int three = Integer.parseInt(string[2]);c.set(one, two, three);c.add(Calendar.DAY_OF_MONTH, day);SimpleDateFormat format = new SimpleDateFormat(formatter);return format.format(c.getTime());}public static Date getNextDay(Date date, int day) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.DAY_OF_MONTH, day);return cal.getTime();}/*** 得到当前的毫秒日期20120201165044734,17位字符串*/public static synchronized String getMillisecond() {return crunttime().toString().replace("-", "").replace(" ", "").replace(":", "").replace("\\.", "");}public static String getDate(Date date) {SimpleDateFormat sdf = new SimpleDateFormat(formatter);return sdf.format(date);}public static String getDateTime(Date date) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return sdf.format(date);}public static String formatDate(Date date, String format) {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(date);}public static String format(String format) {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(crunttime());}public static String getStringDate(Date date) {SimpleDateFormat sdf = new SimpleDateFormat(formatter);String dateStr = sdf.format(date);return dateStr.replace("-", "");}public static String dateStr(String date) {String dateStr = "";if (StringUtils.isNotBlank(date)) {dateStr = " to_date('" + date + " 00:00:00','yyyy-MM-dd HH24:mi:ss') ";}return dateStr;}/*** subtractDate:(得到两个日期相减的结果)** @param @param  minuend(被减数)* @param @param  subtrahend(减数)* @param @param  returnType(返回类型:1-毫秒,2-秒,3-分,4-小时,5-天,6-月,7-年)* @param @return* @return long DOM对象* @throws @since CodingExample Ver 1.1*/public static long subtractDate(Date minuend, Date subtrahend, int returnType) {long result = 0;long millionSecondsForMinuend = minuend.getTime();long millionSecondsForSubtrahend = subtrahend.getTime();long subtract = millionSecondsForMinuend - millionSecondsForSubtrahend;switch (returnType) {case 1:result = subtract;break;case 2:result = subtract / 1000;break;case 3:result = subtract / 1000 / 60;break;case 4:result = subtract / 1000 / 60 / 60;break;case 5:result = subtract / 1000 / 60 / 60 / 24;break;case 6:result = subtract / 1000 / 60 / 60 / 24 / 30;break;case 7:result = subtract / 1000 / 60 / 60 / 24 / 30 / 12;break;default:result = 0;}return result;}/*** 取得当前日期是多少周** @param date* @return*/public static int getWeekOfYear(Date date) {Calendar c = Calendar.getInstance();c.setFirstDayOfWeek(Calendar.MONDAY);/*** 设置一年中第一个星期所需的最少天数,例如,如果定义第一个星期包含一年第一个月的第一天,则使用值 1 调用此方法。* 如果最少天数必须是一整个星期,则使用值 7 调用此方法。**/c.setMinimalDaysInFirstWeek(1);c.setTime(date);return c.get(Calendar.WEEK_OF_YEAR);}/*** 得到某一年周的总数** @param year* @return*/public static int getMaxWeekNumOfYear(int year) {Calendar c = Calendar.getInstance();c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);return getWeekOfYear(c.getTime());}/*** 得到某年某周的第一天** @param year* @param week* @return*/public static Date getFirstDayOfWeek(int year, int week) {Calendar c = Calendar.getInstance();c.set(Calendar.YEAR, year);c.set(Calendar.WEEK_OF_YEAR, week);c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 设置周一c.setFirstDayOfWeek(Calendar.MONDAY);c.set(Calendar.HOUR_OF_DAY, 0);c.set(Calendar.MINUTE, 0);c.set(Calendar.SECOND, 0);c.set(Calendar.MILLISECOND, 0);return c.getTime();}/*** 得到某年某周的最后一天** @param year* @param week* @return*/public static Date getLastDayOfWeek(int year, int week) {Calendar c = Calendar.getInstance();c.set(Calendar.YEAR, year);c.set(Calendar.WEEK_OF_YEAR, week);c.setFirstDayOfWeek(Calendar.MONDAY);c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sundayc.set(Calendar.HOUR_OF_DAY, 0);c.set(Calendar.MINUTE, 0);c.set(Calendar.SECOND, 0);c.set(Calendar.MILLISECOND, 0);return c.getTime();}/*** 得到某年某月的第一天** @param year* @param month* @return*/public static Date getFirstDayOfMonth(int year, int month) {Calendar c = Calendar.getInstance();c.set(Calendar.YEAR, year);c.set(Calendar.MONTH, month - 1);c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));c.set(Calendar.HOUR_OF_DAY, 0);c.set(Calendar.MINUTE, 0);c.set(Calendar.SECOND, 0);c.set(Calendar.MILLISECOND, 0);return c.getTime();}/*** 得到某年某月的最后一天** @param year* @param month* @return*/public static Date getLastDayOfMonth(int year, int month) {Calendar c = Calendar.getInstance();c.set(Calendar.YEAR, year);c.set(Calendar.MONTH, month - 1);c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));c.set(Calendar.HOUR_OF_DAY, 0);c.set(Calendar.MINUTE, 0);c.set(Calendar.SECOND, 0);c.set(Calendar.MILLISECOND, 0);return c.getTime();}/*** 得到某年某季度第一天** @param year* @param quarter* @return*/public static Date getFirstDayOfQuarter(int year, int quarter) {int month;if (quarter > 4) {return null;} else {month = (quarter - 1) * 3 + 1;}return getFirstDayOfMonth(year, month);}/*** 得到某年某季度最后一天** @param year* @param quarter* @return*/public static Date getLastDayOfQuarter(int year, int quarter) {int month;if (quarter > 4) {return null;} else {month = quarter * 3;}return getLastDayOfMonth(year, month);}/*** 得到某年第一天** @param year* @return*/public static Date getFirstDayOfYear(int year) {return getFirstDayOfQuarter(year, 1);}/*** 得到某年最后一天** @param year* @return*/public static Date getLastDayOfYear(int year) {return getLastDayOfQuarter(year, 4);}/*** 获取当月的 天数*/public static int getCurrentMonthDay() {Calendar a = Calendar.getInstance();a.set(Calendar.DATE, 1);a.roll(Calendar.DATE, -1);return a.get(Calendar.DATE);}/*** 根据年 月 获取对应的月份 天数*/public static int getDaysByYearMonth(int year, int month) {Calendar a = Calendar.getInstance();a.set(Calendar.YEAR, year);a.set(Calendar.MONTH, month - 1);a.set(Calendar.DATE, 1);a.roll(Calendar.DATE, -1);return a.get(Calendar.DATE);}/*** 根据日期 找到对应日期的 星期*/public static String getDayOfWeekByDate(String date) {String dayOfweek = "-1";try {SimpleDateFormat myFormatter = new SimpleDateFormat(formatter);Date myDate = myFormatter.parse(date);SimpleDateFormat formatter = new SimpleDateFormat("E");String str = formatter.format(myDate);dayOfweek = str;} catch (Exception e) {logger.info("error: ", e);}return dayOfweek;}public static int getYear(Date date) {Calendar c = Calendar.getInstance();c.setTime(date);return c.get(Calendar.YEAR);}public static int getMonth(Date date) {Calendar c = Calendar.getInstance();c.setTime(date);return c.get(Calendar.MONTH) + 1;}// 获取yf=‘2014-04’前1个月的月份,返回2014-03public static String getPreviousMonth(String date) {int nd = Integer.parseInt(date.substring(0, 4));int yf = Integer.parseInt(date.substring(5, 7));if (yf == 1) {nd = nd - 1;yf = 12;} else {yf = yf - 1;}return getDate(getFirstDayOfMonth(nd, yf)).substring(0, 7);}public static Date getDateByString(String formatter ,String date) {SimpleDateFormat myFormatter = new SimpleDateFormat(formatter);Date myDate = null;try {myDate = myFormatter.parse(date);} catch (ParseException e) {e.printStackTrace();}return myDate;}
}

【zip导出】下载导出包含图片,excel,pdf的zip压缩包相关推荐

  1. thinkphp3.2.3 excel导出,下载文件,包含图片

    关于导出后出错的问题 https://segmentfault.com/q/1010000005330214 https://blog.csdn.net/ohmygirl/article/detail ...

  2. 一键导出资料(图片和PDF)到ZIP

    一键导出所有影像资料并压缩成ZIP格式 思路: 利用Hutool.Freemarker.jsoup.xhtmlrenderer工具简单实现. 先看效果,再看代码: 1. 所需JAR包 <!-- ...

  3. Angular10 + file-saver前端实现html导出word(包含图片)

    场景描述: 在一个即将迎来美好周末的Friday,领导找到我,问我是不是做过html导出word文档的功能,我很诚恳地说做过图片. 项目需求: 项目当中某一个详情页,页面中包含基本内容以及图片,且图片 ...

  4. vue 电子表格Excel的上传导入、导出下载、读取本地Excel、json转Excel

    上传导入Excel 安装插件 npm install xlsx main.js中 // 导入excel插件 import XLSX from 'xlsx' Vue.prototype.$XLSX = ...

  5. POI导出消息列表(包含图片)

    s导出消 消息1对应发送的学生列表 消息2对应发送的学生列表 消息3对应发送的学生列表 ... 消息n对应发送的学生列表 Map<String, List<Map<String, O ...

  6. 文件预览格式太多 前端需要很多插件,有了这一个就够了,kkFileView支持doc,docx,Excel,pdf,txt,zip,rar,图片等等

    官方文档地址:https://kkfileview.keking.cn/zh-cn/docs/home.html gitee项目源码:https://gitee.com/kekingcn/file-o ...

  7. poi根据模板导出word(包含图片、动态生成表格、合并单元格)(亲测有效)

    准备工作: 1.需要的jar(jar包在资源处已上传,可下载) 2.创建docx模板(doc不可以) 第一步:准备好jar(这里面的 ooxml-schemas-1.1.jar 大家可以尝试用poi- ...

  8. h5页面如何预览excel文件_H5 app实现文件预览下载(包括图片、pdf、word、excel、txt格式)...

    本人第一次接触H5 app,一上来就要实现这个功能,就是一脸的黑人问号,只能老办法,去找度娘~. 网上一搜,果然有很多种方法呀.本人用的是壳子是"cordova",因此用这种方法是 ...

  9. 教你用EasyExcel导出包含图片列的excel

    教你用EasyExcel导出包含图片列的excel 前情概要 众所周知,导入及导出功能在后台服务中很常见,博主目前参与的这个项目就有多Excel的导入和导出,但是在我昨天完成需求的时候,突然发现项目里 ...

最新文章

  1. 海量数据处理:从并发编程到分布式系统
  2. AWS加入.NET Foundation企业赞助商计划
  3. Problem D: 编程题B-向量的数量积
  4. 计算机网络实验题教程推介,计算机网络实验教程从原理到实践(附光盘)
  5. mysql end case连接_MySql 中 case when then else end 的用法
  6. 手里有200万,如何理财?
  7. html5 定位 计算距离,HTML5 地理定位+地图 API:计算用户到商家的距离
  8. 寻找反素数python
  9. 区块链技术指南学习(五)双花
  10. html hide特效,jQuery / 动画与特效中的显示show和隐藏hide - 汇智网
  11. Simulink开环控制都不稳----记录一次还没有解决的问题
  12. 在腾讯的八年,我的职业思考!
  13. 2021-09-21
  14. weblogic Unable to obtain lock on
  15. 建设工程法规专科【7】
  16. ContentPane
  17. VO、AO、执行环境和作用域链
  18. java集合之List线程安全性比较总结
  19. 中国南北分界线在哪里,卫星地图带你一探究竟……
  20. 计及源荷不确定性的综合能源生产单元运行调度与容量配置优化研究(Matlab代码实现)

热门文章

  1. UVA 1471 Defense Lines 防线
  2. legacy引导gpt分区_传统Legacy引导和MBR硬盘格式无损更换UEFI和GPT的操作
  3. 元宇宙大热,DiDi message将成为未来世界的连接器
  4. 上品携手SAP领跑服装零售行业
  5. 毕业生之瞳——《技术之瞳——叩开阿里之门之在线笔试》
  6. Elasticsearch+Spring Boot集成实践
  7. 06解决Anaconda3安装完成后在开始菜单找不到的问题
  8. Thinkpad电脑安装ubuntu,遇到问题“Minimal BASH-like line editing is supported”
  9. 曝光中国女性的私密数据-广西富婆多,快上车!
  10. 能温柔的时候,请别尖锐