新建SpringBoot项目主要配置文件和主要工具类(2)

该博客展示了Java项目中的相关代码,包含exception工具类、ExportUtil导出工具类、FileUtil工具类,可实现异常处理、文件导出等功能。还给出了application.yml和application - dev.yml配置文件,对文件大小等进行了设置。

1.exception工具类
public class LcProjectException extends RuntimeException{
public LcProjectException(String message){
super(message);
}
}

2.ExoprtUtil导出工具类
package com.example.lcproject.util;
import com.github.liaochong.myexcel.core.DefaultExcelBuilder;
import com.github.liaochong.myexcel.core.ExcelBuilder;
import com.github.liaochong.myexcel.core.FreemarkerExcelBuilder;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.codec.CharEncoding;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**

  • @author huangz

  • @Description: 导出工具类

  • @date 2019/1/23 12:57
    */
    @Component
    public class ExportUtil {

    public static final String TEMPLATES_FONT = “/templates/simsun.ttf”;//模版字体(宋体)
    public static final String PATH = “/templates/”;//模版路径

    /**

    • ftl模版导出pdf

    • @param response 输出流.

    • @param template 模版的名字.

    • @param model 模版的数据.

    • @throws FileNotFoundException

    • @throws DocumentException
      */
      public void toPdf(HttpServletResponse response, HttpServletRequest request, String template, Map<String, Object> model,String fileName) {
      FileUtil.setResponseHeader(request,response,fileName+".pdf");
      template= ExportUtil.PATH+template;
      String htmlContent = null;
      try {
      htmlContent = getDymaticHtml(template, model);
      } catch (IOException e) {
      e.printStackTrace();
      } catch (TemplateException e) {
      e.printStackTrace();
      }

      ITextRenderer renderer = new ITextRenderer();
      ITextFontResolver fontResolver = renderer.getFontResolver();
      try {
      fontResolver.addFont(TEMPLATES_FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
      } catch (IOException e) {
      e.printStackTrace();
      } catch (DocumentException e) {
      e.printStackTrace();
      }

      renderer.setDocumentFromString(htmlContent);
      renderer.layout();
      try {
      renderer.createPDF(response.getOutputStream());
      } catch (DocumentException e) {
      e.printStackTrace();
      }catch (IOException e){
      e.printStackTrace();
      }
      }

    /**

    • thymeleaf模版导出word
    • // * @param outputStream 输出流.
    • @param template 模版的名字.
    • @param model 数据.
    • @throws FileNotFoundException
    • @throws DocumentException
      */
      public void toWord(HttpServletResponse response, HttpServletRequest request, String template, Map<String, Object> model,String fileName){
      FileUtil.setResponseHeader(request,response,fileName+".doc");
      template= ExportUtil.PATH+template;
      String content = null;
      try {
      content = getDymaticHtml(template, model);
      } catch (TemplateException e) {
      e.printStackTrace();
      }catch (IOException e){
      e.printStackTrace();
      }
      byte b[] = content.getBytes();
      ByteArrayInputStream bais = new ByteArrayInputStream(b);
      POIFSFileSystem poifs = new POIFSFileSystem();
      DirectoryEntry directory = poifs.getRoot();
      try {
      DocumentEntry documentEntry = directory.createDocument(
      “WordDocument”, bais);
      poifs.writeFilesystem(response.getOutputStream());
      bais.close();
      } catch (IOException e){
      e.printStackTrace();
      }
      }

    /**

    • ftl模版导出excel

    • @param response 输出流.

    • @param template 模版的名字.

    • @param model 模版的数据.

    • @isFreezeFirstRow 是否冻结首行
      */
      public void toExcel(HttpServletRequest request,HttpServletResponse response, String template, Map<String, ?> model, String fileName,Boolean isFreezeFirstRow) {

      template= ExportUtil.PATH+template;
      String[] filePath = this.splitFilePath(template);
      template=filePath[0]+"/"+filePath[1];
      FileUtil.setResponseHeader(request,response,fileName+".xlsx");
      ExcelBuilder excelBuilder = new FreemarkerExcelBuilder();
      Workbook workbook = excelBuilder.template(template).useDefaultStyle().build(model);
      workbook.getSheetAt(0).createFreezePane(0,1);
      try {
      workbook.write(response.getOutputStream());
      } catch (IOException e) {
      e.printStackTrace();
      }
      }

    /**

    • 导出excel默认格式(在实体类用注解)
    • @ExcelTable(sheetName = “要导出的文件名字”)
    • @ExcelColumn(title = “列名”,order = 1,dateFormatPattern = “yyyy-MM-dd”)
    • @param response 输出流.
    • @param c 要导出的类.
    • @param dataList 模版的数据.
      */
      public void toDefaultExcel(HttpServletRequest request, HttpServletResponse response, Class<?> c, List<?> dataList, String fileName) {
      Workbook workbook = DefaultExcelBuilder.of©.build(dataList);
      workbook.getSheetAt(0).createFreezePane(0,1);
      FileUtil.setResponseHeader(request,response,fileName+".xlsx");
      try {
      workbook.write(response.getOutputStream());
      } catch (IOException e) {
      e.printStackTrace();
      }
      }

    /**

    • 导出excel默认格式(在实体类用注解)

    • @param titles 自定义的标题

    • @param response 输出流.

    • @param c 要导出的类.

    • @param dataList 模版的数据.
      /
      public void toDefaultExcel(List titles,List field,HttpServletRequest request, HttpServletResponse response, Class<?> c, List<?> dataList, String fileName) {
      Workbook workbook = DefaultExcelBuilder.of©.titles(titles).fieldDisplayOrder(field).build(dataList);
      workbook.getSheetAt(0).createFreezePane(0,1);
      FileUtil.setResponseHeader(request,response,fileName+".xlsx");
      try {
      workbook.write(response.getOutputStream());
      } catch (IOException e) {
      e.printStackTrace();
      }
      }
      /
      *

    • 生成动态html页面

    • 模版freemarker获取动态html方法

    • @param model 数据

    • @return

    • @throws IOException

    • @throws TemplateException
      */
      public String getDymaticHtml(String templatePath, Map<String, ?> model) throws IOException, TemplateException {
      Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
      cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
      cfg.setDefaultEncoding(CharEncoding.UTF_8);

      String[] filePath = this.splitFilePath(templatePath);
      cfg.setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), filePath[0]);
      Template template = cfg.getTemplate(filePath[1]);
      Writer writer = new StringWriter();
      // 将模版与数据进行匹配整合
      template.process(model, writer);
      writer.flush();
      writer.close();
      return writer.toString();
      }

    /**

    • 分离文件路径
    • @param path 文件路径
    • @return String[]
      */
      String[] splitFilePath(String path) {
      if (Objects.isNull(path)) {
      throw new NullPointerException();
      }
      path = path.replaceAll("/+", “/”);//访问路径中有可能有多个/
      int lastPackageIndex = path.lastIndexOf("/");
      if (lastPackageIndex == -1 || lastPackageIndex == path.length() - 1) {
      throw new IllegalArgumentException();
      }
      String basePackagePath = path.substring(0, lastPackageIndex);
      String templateName = path.substring(lastPackageIndex);
      return new String[]{basePackagePath, templateName};
      }
      }
      3.FileUtil工具类
      package com.example.lcproject.util;

import com.example.lcproject.exception.LcProjectException;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.
;

/**
*
*/
public class FileUtil {
public static final String EMPTY = “”;

public static final String BLANK=" ";

public static final String PERCENT="%";

public static final String YYYY_MM_DD = "yyyy-MM-dd";

public static final String SLASH = "/";

public static final String TRANSVERSE_LINE = "-";

public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

/*
**表示doc xls ppt**
 */
private static final String DEPP = "depp";

/*
表示Microsoft 1997-2003格式下的doc xls ppt
 */
public static final String KB = "KB";
public static final String MB = "MB";
public static final String ISO = "ISO8859-1";
public static final String CONTRNT_TYPE = "multipart/form-data";
public static final String MSIE = "MSIE";
public static final String TRIDENT = "TRIDENT";
public static final String EDGE = "EDGE";
public static final String COMMA_SYMBOL = ",";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String ATTACHMENT_FILENAME = "attachment;filename=";
public static final String XLS = ".xls";
/**
 * 创建目录,根据日期每天生成一个目录用来存放上传的文件
 *
 * @return 目录的名称
 */
public static String createDir() {
    Calendar now = Calendar.getInstance();
    return now.get(Calendar.YEAR) + SLASH + (now.get(Calendar.MONTH) + 1) + SLASH + now.get(Calendar.DAY_OF_MONTH);
}

/**
 * 得到当前年
 *
 * @return
 */
public static int getYear() {
    Calendar now = Calendar.getInstance();
    return now.get(Calendar.YEAR);
}

/**
 * 根据传入时间得到年份
 *
 * @return
 */
public static int getYearByDate(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    return c.get(Calendar.YEAR);
}


/**
 * 为了保证文件名称不重复,采用uuid方式生成文件名
 *
 * @param originName 上传文件的名称
 * @return 新的文件名称
 */
public static String createFileName(String originName) {

    return getUUID();
}

/**
 * 得到文件后缀
 *
 * @param originName
 * @return
 */
public static String getFileSuffix(String originName) {
    int index = originName.lastIndexOf(".");
    if (index == -1) {
        throw new LcProjectException("文件路径异常");
    }
    String suffix = originName.substring(index);
    return suffix;
}


/**
 * 去掉文件后缀
 * @param fileName
 * @return
 */
public static String getFileName(String originName) {
    int index = originName.lastIndexOf(".");
    String substring = originName.substring(0, index);
    return substring;
}

/**
 * MultipartConfigFactory#parseSize()
 *
 * @param size
 * @return
 */
public static long parseSize(String size) {
    Assert.hasLength(size, "Size must not be empty");
    size = size.toUpperCase();
    if (size.endsWith(KB)) {
        return Long.valueOf(size.substring(0, size.length() - 2)) * 1024;
    }
    if (size.endsWith(MB)) {
        return Long.valueOf(size.substring(0, size.length() - 2)) * 1024 * 1024;
    }
    return Long.valueOf(size);
}

/**
 * 字符串转date
 *
 * @param date yyyy-MM-dd HH:mm:ss
 * @return
 */
public static Date stringToDate(String date) {
    try {
        return dateFormat.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

public static String dateToString(Date date) {
    return dateFormat.format(date);
}

public static LocalDateTime dateToLocalDateTime(Date date) {
    Instant instant = date.toInstant();
    ZoneId zoneId = ZoneId.systemDefault();
    return instant.atZone(zoneId).toLocalDateTime();
}

public static Date localDateTimeToDate(LocalDateTime localDateTime) {
    ZoneId zoneId = ZoneId.systemDefault();
    ZonedDateTime zdt = localDateTime.atZone(zoneId);

    return Date.from(zdt.toInstant());
}

/**
 * 传入LocalDateTime加上相应天数
 *
 * @param ldt  LocalDateTime时间
 * @param days 天数
 * @return
 */
public static LocalDateTime localDateTimePlusDays(LocalDateTime ldt, int days) {
    return ldt.plus(days, ChronoUnit.DAYS);
}

/**
 * 传入LocalDateTime减去相应天数
 *
 * @param ldt  LocalDateTime时间
 * @param days 天数
 * @return
 */
public static LocalDateTime localDateTimeMinusDays(LocalDateTime ldt, int days) {
    return ldt.minus(days, ChronoUnit.DAYS);
}


/**
 * 得到uuid
 * @return
 */
public static String getUUID(){
    String uuid = UUID.randomUUID().toString(); //获取UUID并转化为String对象
    uuid = uuid.replace(TRANSVERSE_LINE, EMPTY);//因为UUID本身为32位只是生成时多了“-”,所以将它们去点就可
    return uuid;
}

/**
 * 设置文件下载响应信息
 *
 * @param httpServletRequest
 * @param httpServletResponse
 * @param fileName
 */
public static void setResponseHeader(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String fileName) {
    try {
        String agent = httpServletRequest.getHeader("USER-AGENT");
        if (agent != null) {
            agent = agent.toUpperCase();
            if (null == agent) {//中文文件名
                fileName = new String(fileName.getBytes("UTF-8"), FileUtil.ISO);
            } else if (-1 != agent.indexOf(FileUtil.MSIE) || -1 != agent.indexOf(FileUtil.TRIDENT) || -1 != agent.indexOf(FileUtil.EDGE)) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), FileUtil.ISO);
            }
        }
        httpServletResponse.setContentType(FileUtil.CONTRNT_TYPE);
        httpServletResponse.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + fileName);
    } catch (IOException e) {
        throw new LcProjectException("io异常");
    }
}

/**
 * 通过反射得到字段值为1的字段名导出时使用
 * @param obj
 * @return
 */
public static List<String> getFieldName(Object obj) {
    if (obj == null) return null;
    Field[] fields = obj.getClass().getDeclaredFields();
    List<String> list=new ArrayList<>();
    for (int j = 0; j < fields.length; j++) {
        fields[j].setAccessible(true);

// // 字段名
// System.out.print(fields[j].getName() + “,”);
// 字段值
if (fields[j].getType().getName().equals(// String 类型
String.class.getName())) {
try {
System.out.print(fields[j].get(obj));
if(“1”.equals(fields[j].get(obj))){
list.add(fields[j].getName());
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else if (fields[j].getType().getName().equals(
Integer.class.getName())
|| fields[j].getType().getName().equals(“int”)) {// int 类型
try {
System.out.println(fields[j].getInt(obj));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
// 其他类型。。。
}
return list;
}

/**
 * 拷贝文件
 * @param sourceFile
 * @param newFile
 */
public static void copyFile(File sourceFile,File newFile){
    try {
        FileUtils.copyFile(sourceFile, newFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * 将file文件转为byte数组
 * @param file
 */
public static byte[] fileToByte(File file){
    try {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = -1;
        while((len = fis.read(b)) != -1) {
            bos.write(b, 0, len);
        }
       return bos.toByteArray();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }
    return null;
}

}
3.application.yml配置文件
spring:
profiles:
active: dev
http:
multipart:
max-file-size: 500Mb
max-request-size: 1000Mb
4.application-dev.yml配置文件
在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值