SpringBoot导出Excel表格到指定路径的代码详解
作者:龙域、白泽
Spring Boot导出Excel通常涉及到使用第三方库如Apache POI或者XlsxWriter等,它们能帮助你在Spring应用中生成并下载Excel文件,那么SpringBoot如何导出Excel表格到指定路径,本文将给大家详细的介绍一下
导入依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>
自定义 @Excel 注解
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Excel { /** * 导出到Excel中的名字 */ String name() default ""; /** * 日期格式, 如: yyyy-MM-dd */ String dateFormat() default ""; /** * 字典的key值 */ String dictKey() default ""; /** * 读取内容转表达式 (如: 0=男,1=女,2=未知) */ String dictExp() default ""; }
Excel工具类
/** * Excel的工具类 */ public class ExcelUtil<T> { /** * 工作薄 */ private Workbook wb; /** * 工作表 */ private Sheet sheet; /** * 需要导出的数据 */ private List<T> exportList; /** * 对象的class对象 */ private Class<T> clazz; /** * 被选中需要导出的字段名称 */ private Map<String, Object> checkedFieldsName; /** * 被选中需要导出的字段对象 */ private List<Field> checkedFields; /** * 包含需要字典转换的字段对象 */ private List<Field> fieldsContainDict; /** * 对象中的字典值 */ private Map<String, Map<String, String>> dicts; private ExcelUtil(){ } public ExcelUtil(Class<T> clazz){ this.clazz = clazz; } /** * * @param list * @param sheetName * @param fieldsName */ public void exportExcel(List<T> list, Map<String, Object> fieldsName, String sheetName){ // 初始化数据 init(list, sheetName, fieldsName); // 转换字典值 try { convertDict(); } catch (IllegalAccessException e) { e.printStackTrace(); } // sheet第一行加入名称数据 createTopRow(); // sheet其他行,添加目标数据 try { createOtherRow(); } catch (IllegalAccessException e) { e.printStackTrace(); } // 导出wb try(OutputStream outFile = new FileOutputStream(generateFileName())){ wb.write(outFile); } catch (IOException e) { e.printStackTrace(); } finally { try { wb.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 添加导出数据 */ private void createOtherRow() throws IllegalAccessException { for (int rowNum = 1; rowNum <= exportList.size(); rowNum++) { Row row = sheet.createRow(rowNum); T t = exportList.get(rowNum - 1); for (int colNum = 0; colNum < checkedFields.size(); colNum++) { Cell cell = row.createCell(colNum); Field field = checkedFields.get(colNum); field.setAccessible(true); // 单元格设置值 addCell(cell, field, t); } } } /** * 单元格中添加数据 * * @param cell 单元格 * @param field 字段 * @param t list中的一条数据 */ private void addCell(Cell cell, Field field, T t) throws IllegalAccessException { Class<?> fieldType = field.getType(); if (String.class == fieldType) { cell.setCellValue((String) field.get(t)); } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) { cell.setCellValue((Integer) field.get(t)); } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) { cell.setCellValue((Long) field.get(t)); } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) { cell.setCellValue((Double) field.get(t)); } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) { cell.setCellValue((Float) field.get(t)); } else if (Date.class == fieldType) { String dateFormat = field.getAnnotation(Excel.class).dateFormat(); cell.setCellValue(dateFormat((Date) field.get(t), dateFormat)); } } /** * 时间格式转换 * @param date 日期 * @param dateFormat 日期格式 * @return */ private String dateFormat(Date date, String dateFormat) { if (dateFormat == null || "".equals(dateFormat)) { dateFormat = "yyyy-MM-dd HH:mm:ss"; } SimpleDateFormat df = new SimpleDateFormat(dateFormat); return df.format(date); } /** * sheet第一行加入名称数据 */ private void createTopRow() { Row row = sheet.createRow(0); Map<String, CellStyle> styles = createStyles(wb); for (int index = 0; index < checkedFields.size(); index++) { Cell cell = row.createCell(index); cell.setCellValue(checkedFields.get(index).getAnnotation(Excel.class).name()); System.out.println(styles.get("header")); cell.setCellStyle(styles.get("header")); } } /** * 转换字典值 * 将数据中字典值转化为对应的值(注:字典值应为String格式) */ private void convertDict() throws IllegalAccessException { for (Field field : fieldsContainDict) { Excel annotation = field.getAnnotation(Excel.class); String dictKey = annotation.dictKey(); field.setAccessible(true); for (T t : exportList) { // 获取字段值 String o = (String) field.get(t); field.set(t, dicts.get(dictKey).get(o)); } } } /** * 将数据导出Excel * * @param list 需要导出的数据 * @param sheetName 工作表名称 */ public void exportExcel(List<T> list, String sheetName){ exportExcel(list, null, sheetName); } /** * 将数据导出Excel * * @param list 需要导出的数据 */ public void exportExcel(List<T> list) { exportExcel(list, null, "sheet"); } /** * 初始化 */ public void init(List<T> list ,String sheetName, Map<String, Object> fieldsName){ this.checkedFieldsName = fieldsName; this.exportList = list; // 初始化导出数据 initExportList(); // 初始化工作薄 initWorkbook(); // 初始化工作表 initSheet(sheetName); // 初始化checkedFields, fieldsContainDict initFields(); // 根据注解生成生成字典 generateObjDict(); } /** * 初始化导出数据 */ private void initExportList(){ // 防止导出过程中出现空指针 if(Objects.isNull(this.exportList)) { this.exportList = new ArrayList<>(); } } /** * 初始化工作簿 */ private void initWorkbook(){ this.wb = new SXSSFWorkbook(); } /** * 初始化工作表 */ private void initSheet(String sheetName){ this.sheet = wb.createSheet(sheetName); } /** * 初始化checkedFields, fieldsContainDict * fieldsContainDict含有字典表达式的字段 * checkedFields用户选中的字段 * 1.如果checkedFieldsName没有定义(未自定义导出字段),所有字段全部导出 * 2.如果checkedFieldsName进行了定义,根据定义字段进行导出 */ private void initFields(){ // 获取对象所有字段对象 Field[] fields = clazz.getDeclaredFields(); // 过滤出checkedFields this.checkedFields = Arrays. asList(fields). stream(). filter(item -> { if(!Objects.isNull(this.checkedFieldsName)) { if (item.isAnnotationPresent(Excel.class)) { return checkedFieldsName.containsKey(item.getName()); } } else { return item.isAnnotationPresent(Excel.class); } return false; }) .collect(Collectors.toList()); // 过滤出fieldsContainDict for (Field declaredField : clazz.getDeclaredFields()) { if(declaredField.getAnnotation(Excel.class) != null) { System.out.println(declaredField.getAnnotation(Excel.class).dictExp()); } } this.fieldsContainDict = Arrays .asList(clazz.getDeclaredFields()) .stream() .filter(item -> !"".equals(item.getAnnotation(Excel.class) != null? item.getAnnotation(Excel.class).dictExp() : "")) .collect(Collectors.toList()); } /** * 通过扫描字段注解生成字典数据 */ private void generateObjDict(){ if(fieldsContainDict.size() == 0) { return; } if(dicts == null) { dicts = new HashMap<>(); // Map<String, List<Map<String, String>>> } for (Field field : fieldsContainDict) { String dictKey = field.getAnnotation(Excel.class).dictKey(); String exps = field.getAnnotation(Excel.class).dictExp(); String[] exp = exps.split(","); Map<String, String> keyV = new HashMap<>(); dicts.put(dictKey, keyV); for (String s : exp) { String[] out = s.split("="); keyV.put(out[0], out[1]); } System.out.println("字典值:"+ dicts); } } /** * 创建表格样式 * * @param wb 工作薄对象 * @return 样式列表 */ private Map<String, CellStyle> createStyles(Workbook wb) { Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); // 数据格式 CellStyle style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setBorderRight(BorderStyle.THIN); style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderLeft(BorderStyle.THIN); style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderTop(BorderStyle.THIN); style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderBottom(BorderStyle.THIN); style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); Font dataFont = wb.createFont(); dataFont.setFontName("Arial"); dataFont.setFontHeightInPoints((short) 10); style.setFont(dataFont); styles.put("data", style); // 表头格式 style = wb.createCellStyle(); style.cloneStyleFrom(styles.get("data")); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); Font headerFont = wb.createFont(); headerFont.setFontName("Arial"); headerFont.setFontHeightInPoints((short) 10); headerFont.setBold(true); headerFont.setColor(IndexedColors.WHITE.getIndex()); style.setFont(headerFont); styles.put("header", style); return styles; } /** * 生成随机名称,防止文件复写 * @return 导出路径 */ private String generateFileName(){ return "D:\\" + UUID.randomUUID().toString().replace("-", "") + ".xlsx"; } }
在实体类上标注自定义注解
@Data @NoArgsConstructor @AllArgsConstructor public class Student { @Excel(name = "姓名") private String name; @Excel(name = "年龄") private Integer age; @Excel(name = "出生日期", dateFormat = "yyyy-MM-dd") private Date birthday; @Excel(name = "性别", dictKey = "sex", dictExp = "1=男,2=女") // 注意这里是用String类型【【坑】】 private String sex; }
生成目标Excel表格
@Log(title = "用户管理", businessType = BusinessType.EXPORT) @RequiresPermissions("system:user:export") @PostMapping("/export") @ResponseBody public AjaxResult export(SysUser user) { List<SysUser> list = userService.selectUserList(user); ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class); return util.exportExcel(list, "用户数据"); }
测试
public static void main(String[] args) { ArrayList<Student> data = new ArrayList<>(); Student student = new Student(); student.setName("tom"); student.setAge(19); // 在表格中1会变成男 student.setSex("1"); student.setBirthday(new Date()); data.add(student); ExcelUtil<Student> util = new ExcelUtil<>(Student.class); util.exportExcel(data, "人员信息表"); }
若不自定义导出的字段,,工具将会把所有带有
Excel
注解的字段进行导出,如上
指定导出字段
public static void main(String[] args) { ArrayList<Student> data = new ArrayList<>(); Student student = new Student(); student.setName("tom"); student.setAge(19); student.setSex("1"); student.setBirthday(new Date()); data.add(student); // 需要导出字段的名称,放入map的key中即可(这里只导出姓名和性别) Map<String, Object> fieldsName = new HashMap<>(); fieldsName.put("name", null); fieldsName.put("sex", null); ExcelUtil<Student> util = new ExcelUtil<>(Student.class); // 将fieldsName放入方法中 util.exportExcel(data, fieldsName,"人员信息表"); }
到此这篇关于SpringBoot导出Excel表格到指定路径的代码详解的文章就介绍到这了,更多相关SpringBoot导出Excel指定路径内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!