23.从零开始学springboot-excel导入导出

前言

上一章作者分享了mybatis通用mapper的实用。在实际开发中,我们常常会用到excel导入导出相关的功能,本章,作者将分享一个实用的excel操作案例,实现excel的导入导出功能。

亮点:

  • excel导入反射java实体
  • excel导出使用模版

这边简单解释下。
excel导入反射java实体:
首先我们讲下正常实现excel导入的方法,如下伪代码

public List<Student> importExcel(File excelFile, Student student){
    List<Student> list = new ArrayList<Student>();
    for (excelFile) {
        Student s = new Student();
        //excel的第一行的第一列为name
        student.name = excelFile.row[0].column[0];
        //excel的第一行的第二列为age
        student.age = excelFile.row[0].column[1];
        list.add(s);
    }
    return list;
}

可以看到,我们实现了将excel数据列转换为student实体的逻辑。那么,问题来了,以后我想转为teacher实体怎么办?在写一个类似的方法?可以看出,这种方式在方法体内部实现实体类属性与excel列的绑定,很不灵活。那么,能不能传入一个实体类,在运行时,动态的获取该实体的属性实现绑定呢?。此时就很有必要了解java的反射机制了。
JAVA反射机制是在运行状态中,对于任意一个实体类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性。
我们再看看利用反射机制实现excel导入

public  <T extends Object> List<T> importExcel(File excelFile, Class<T> clazz) {
    List<T> list = new ArrayList<>();
    //获取类的所有属性
    Field[] fields = clazz.getDeclaredFields();
    T obj = null;
    for (excelFile){
        // 创建实体
        obj = clazz.newInstance();
        for (Field f : fields) {
            //属性赋值,实现属性和excel列的绑定关系
        }
        list.add(obj);
    }
    return list;
}

可以看到,利用反射机制实现的导入方法更加灵活,这样就可以使其更加通用。

excel导出使用模版
实现过excel导出功能的可能都知道,excel最麻烦的就是编写样式,尤其是样式复杂的表格。仔细观察表格,你会发现,正常复杂的都是表头样式,往往是这样的(举个简单的例子)


16747124-9a331754e93810e7.png
4.png

然后下半部分可能就是正常的列表展示。
那么我们能不能把这复杂的部分抽出来,单独由人工来做(毕竟office建立这么一个表格so easy,用代码去画简直抓狂。),而后,我们代码读取这个表格,动态填充数据呢?答案,是肯定的。在接下来的案例中你会看到这样的实现。

目录结构

16747124-2d2e1fd64fac9dd7.png
1.png

添加依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

        <!-- SpringBoot通用Mapper依赖 -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.5</version>
        </dependency>

        <!-- excel依赖 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <!-- 实用工具 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>  
16747124-8f7cc6898d5714f6.png
2.png

这里我们除了使用了poi excel的依赖,还使用了上章用过的通用mapper依赖,以及lombok依赖,关于lombok依赖,你可以简单理解为一个工具包,这样我们编写实体类时只需要使用

@Setter
@Getter

两个注解即可自动实现类属性的set和get方法,省了不少事。

添加配置

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

完善代码

我们先实现excel的工具类

utils/excel/ExcelAnnotation

package com.mrcoder.sbmexcel.utils.excel;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelAnnotation {

    /**
     * 列索引
     *
     * @return
     */
    public int columnIndex() default 0;

    /**
     * 列名
     *
     * @return
     */
    public String columnName() default "";

}

ExcelAnnotation这个类实现了一个自定义的注解,定义了两个属性,这样我们可以在实体类中使用

//columnIndex定义excel的列,columnName定义表列名称
@ExcelAnnotation(columnIndex = 1, columnName = "姓名")
private String name;

意思就是导入的excel第二列对应数据表的name列。
此处注意,excel索引是从0开始的。

我们看下需要导入的excel表格结构


16747124-e04564c69fc71a77.png
3.png

第一列需要是我们无需导入的,所以,我们定义实体类时,excel注解从1开始。

接下来我们定义实体类
model/Excel

package com.mrcoder.sbmexcel.model;

import com.mrcoder.sbmexcel.utils.excel.ExcelAnnotation;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Setter
@Getter
@Table(name = "excel")
@Accessors(chain = true)
public class Excel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
  
    @ExcelAnnotation(columnIndex = 1, columnName = "姓名")
    private String name;

    @ExcelAnnotation(columnIndex = 2, columnName = "年龄")
    private Integer age;

    @ExcelAnnotation(columnIndex = 3, columnName = "身高")
    private Double height;

    @ExcelAnnotation(columnIndex = 4, columnName = "体重")
    private Double weight;

    @ExcelAnnotation(columnIndex = 5, columnName = "学历")
    private String edu;
    private Date createTime;
    private Date updateTime;
    private Integer status;
}

从实体类中可以看出,我们使用了

@Setter
@Getter

lombok注解,所以在该实体中无需手写get和set方法。

然后我们实现excel读取反射成实体的工具类
utils/excel/ExcelUtil

package com.mrcoder.sbmexcel.utils.excel;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
/**
 * Excel 工具类
 *
 * @author mrcoder
 * @version 1.0 2019.05.29
 */
public class ExcelUtil {

    /**
     * 读取excel反射实体
     *
     * @param file  MultipartFile
     * @param clazz entity
     * @return
     * @throws RuntimeException
     */
    public static <T extends Object> List<T> readExcelObject(MultipartFile file, Class<T> clazz) {

        // 存储excel数据
        List<T> list = new ArrayList<>();
        Workbook wookbook = null;
        InputStream inputStream = null;

        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException("文件读取异常");
        }

        // 根据excel文件版本获取工作簿
        if (file.getOriginalFilename().endsWith(".xls")) {
            wookbook = xls(inputStream);
        } else if (file.getOriginalFilename().endsWith(".xlsx")) {
            wookbook = xlsx(inputStream);
        } else {
            throw new RuntimeException("非excel文件");
        }

        // 得到一个工作表
        Sheet sheet = wookbook.getSheetAt(0);

        // 获取行总数
        int rows = sheet.getLastRowNum() + 1;
        Row row;

        // 获取类所有属性
        Field[] fields = clazz.getDeclaredFields();

        T obj = null;
        int coumnIndex = 0;
        Cell cell = null;
        ExcelAnnotation excelAnnotation = null;
        for (int i = 1; i < rows; i++) {
            // 获取excel行
            row = sheet.getRow(i);
            //此处用来过滤空行
            Cell cell0 = row.getCell(0);
            cell0.setCellType(CellType.STRING);
            Cell cell1 = row.getCell(1);
            cell1.setCellType(CellType.STRING);
            if (cell0.getStringCellValue() == "" && cell1.getStringCellValue() == "") {
                continue;
            }
            try {
                // 创建实体
                obj = clazz.newInstance();
                for (Field f : fields) {
                    // 设置属性可访问
                    f.setAccessible(true);
                    // 判断是否是注解
                    if (f.isAnnotationPresent(ExcelAnnotation.class)) {
                        // 获取注解
                        excelAnnotation = f.getAnnotation(ExcelAnnotation.class);
                        // 获取列索引
                        coumnIndex = excelAnnotation.columnIndex();
                        // 获取单元格
                        cell = row.getCell(coumnIndex);
                        // 设置属性
                        setFieldValue(obj, f, wookbook, cell);
                    }
                }
                System.out.println(obj);
                // 添加到集合中
                list.add(obj);
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("excel文件内容出错");
            }
        }
        try {
            //释放资源
            wookbook.close();
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 绑定实体值
     *
     * @param obj      Object
     * @param f        Field
     * @param wookbook Workbook
     * @param cell     Cell
     * @return
     * @throws RuntimeException
     */
    private static void setFieldValue(Object obj, Field f, Workbook wookbook, Cell cell) {
        try {

            cell.setCellType(CellType.STRING);

            if (f.getType() == byte.class || f.getType() == Byte.class) {

                f.set(obj, Byte.parseByte(cell.getStringCellValue()));

            } else if (f.getType() == int.class || f.getType() == Integer.class) {

                f.set(obj, Integer.parseInt(cell.getStringCellValue()));

            } else if (f.getType() == Double.class || f.getType() == double.class) {

                f.set(obj, Double.parseDouble(cell.getStringCellValue()));

            } else if (f.getType() == BigDecimal.class) {

                f.set(obj, new BigDecimal(cell.getStringCellValue()));

            } else {

                f.set(obj, cell.getStringCellValue());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对excel 2003处理
     */
    private static Workbook xls(InputStream is) {
        try {
            // 得到工作簿
            return new HSSFWorkbook(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对excel 2007处理
     */
    private static Workbook xlsx(InputStream is) {
        try {
            // 得到工作簿
            return new XSSFWorkbook(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

该工具类接受上传excel文件,以及实体类参数,主要就是将每一行的excel数据转换成一个实体,这样方便我们后续批量入库操作。

mapper/ExcelMapper

package com.mrcoder.sbmexcel.mapper;
import com.mrcoder.sbmexcel.model.Excel;
import tk.mybatis.mapper.additional.insert.InsertListMapper;
import tk.mybatis.mapper.common.ExampleMapper;
import tk.mybatis.mapper.common.Mapper;

public interface ExcelMapper extends Mapper<Excel>, InsertListMapper<Excel>, ExampleMapper<Excel> {
}

service/ExcelService

package com.mrcoder.sbmexcel.service;


import com.mrcoder.sbmexcel.mapper.ExcelMapper;
import com.mrcoder.sbmexcel.model.Excel;
import com.mrcoder.sbmexcel.utils.excel.ExcelUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ExcelService {


    @Autowired
    private ExcelMapper excelMapper;


    //excel导入
    public int importExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile excel = multipartRequest.getFile("filename");

        try {
            List<Excel> excelData = ExcelUtil.readExcelObject(excel, Excel.class);
            //检查每列数据
            for (int i = 0; i < excelData.size(); i++) {
                excelData.get(i).setStatus(1);
                Date time = new Date();
                excelData.get(i).setCreateTime(time);
                excelData.get(i).setUpdateTime(time);
            }
            //批量导入
            return excelMapper.insertList(excelData);

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    //excel导入
    public void exportExcel(HttpServletResponse response) {
        try {
            // 1.读取Excel模板
            File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "excel/export.xlsx");
            InputStream in = new FileInputStream(file);
            XSSFWorkbook wb = new XSSFWorkbook(in);
            // 2.读取模板里面的所有Sheet
            XSSFSheet sheet = wb.getSheetAt(0);
            // 3.设置公式自动读取
            sheet.setForceFormulaRecalculation(true);
            // 4.向相应的单元格里面设置值
            XSSFRow row;

            // 5.得到第二行
            row = sheet.getRow(1);
            // 6.设置单元格属性值和样式
            row.getCell(1).setCellValue("张三");
            row.getCell(3).setCellValue("18");
            row.getCell(6).setCellValue("本科");
            row.getCell(8).setCellValue(new Date());

            row = sheet.getRow(2);
            row.getCell(1).setCellValue("1511xxxx234");
            row.getCell(3).setCellValue("广东");
            row.getCell(6).setCellValue("本科");

            row = sheet.getRow(3);
            row.getCell(1).setCellValue("180");
            row.getCell(3).setCellValue("已婚");
            row.getCell(6).setCellValue("深圳");
            row.getCell(8).setCellValue("2");

            row = sheet.getRow(4);
            row.getCell(1).setCellValue("60");
            row.getCell(3).setCellValue("中国");
            row.getCell(6).setCellValue("其它");
            row.getCell(8).setCellValue("备注");

            //单元格合并
            row = sheet.getRow(6);
            row.getCell(0).setCellValue("合并列");
            CellRangeAddress region = new CellRangeAddress(6, 6, 0, 5);
            sheet.addMergedRegion(region);

            //单元格设置背景色
            CellStyle style = wb.createCellStyle();
            style.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            row.getCell(0).setCellStyle(style);

            //设置单元格边框
            row = sheet.getRow(8);
            XSSFCellStyle style2 = wb.createCellStyle();
            style2.setBorderBottom(BorderStyle.DOUBLE);
            style2.setBorderRight(BorderStyle.DOUBLE);
            style2.setBorderLeft(BorderStyle.DOUBLE);
            style2.setBorderTop(BorderStyle.DOUBLE);
            style2.setBottomBorderColor(IndexedColors.SKY_BLUE.getIndex());
            style2.setRightBorderColor(IndexedColors.SKY_BLUE.getIndex());
            row.getCell(0).setCellStyle(style2);

            // 7.设置sheet名称和单元格内容
            wb.setSheetName(0, "测试");

            String fileName = new String(("export-" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
                    .getBytes(), "UTF-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "No-cache");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream out = response.getOutputStream();
            wb.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

ExcelService实现了导入导出功能的封装。导入功能无需多说,导出实现了读取模版,填充数据,以及对Excel 表格的一些合并,样式修改等功能~

最后,我们完成controller
ExcelController

package com.mrcoder.sbmexcel.controller;
import com.mrcoder.sbmexcel.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class ExcelController {
    @Autowired
    private ExcelService excelService;
    @PostMapping("/importExcel")
    public int importExcel(HttpServletRequest request) {
        return excelService.importExcel(request);
    }
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        excelService.exportExcel(response);
    }
}

运行

http://localhost:8080/importExcel 导入

16747124-573b1acd4821c1f0.png
3.png

http://localhost:8080/exportExcel 导出

16747124-ba4cfcc95eeb9788.png
4.png

项目地址

https://github.com/MrCoderStack/SpringBootDemo/tree/master/sbm-excel

请关注我的订阅号

16747124-b89acf15e2272701.png
订阅号.png

猜你喜欢

转载自blog.csdn.net/weixin_33969116/article/details/91007669
今日推荐