使用Springboot整合POI对数据的导入导出Excel文件笔记

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

一、Excel2003版与Excel2007版对比

1.Excel2003版扩展名.xls;Excel2007版扩展名.xlsx。
2.Excel2003版只能打开.xls后缀的文件;Excel2007版能打开.xlsx和.xls。
3.Excel2003版是二进制格式,存储量少;Excel2007版基于xml压缩的,存储量大,占用空间少,操作效率高。
本次只做Springboot对Excel2007版操作;不执行对数据库操作

二、步骤

1.创建一个新的Springboot项目,我使用前期创建好的hello-rabbit,导入核心依赖

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.2.RELEASE</version>
		<relativePath/> 
	</parent>
	
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		
		<!--spring boot web的依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<!--Apache Poi 依赖-->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>4.0.1</version>
		</dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.1</version>
        </dependency>

2.创建一个实体类Teacher.java,与Excel数据对称

package com.basic.hellorabbit.entity;

import lombok.Data;
/**
* @Description:    老师类
* @Author:         Joe
* @CreateDate:     2020/3/20 15:09
*/
@Data
public class Teacher {

    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    private String subject;

    public Teacher() {
    }

    public Teacher(Integer id, String name, Integer age, String sex, String subject) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.subject = subject;
    }
}

3.创建一个封装类ExcelDatas.java,用于给工具类整理数据

package com.basic.hellorabbit.entity;

import lombok.Data;

import java.util.List;
/**
* @Description:    数据操作类
* @Author:         Joe
* @CreateDate:     2020/3/20 11:12
*/
@Data
public class ExcelDatas {
    /**
     * 文件名
     */
    private String fileName;
    /**
     * 数据的表头(类属性)
     */
    private String[] head;
    /**
     * 数据集合
     */
    private List<Teacher> datas;


}

4.创建一个工具类(创建读取Excel标题,表头,行列数据)ExcelUtil.java,整合数据操作
这个不是很全面,大家可以去封装更丰富的样式

package com.basic.hellorabbit.util;

import com.basic.hellorabbit.entity.ExcelDatas;
import com.basic.hellorabbit.entity.Teacher;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import static org.apache.poi.ss.usermodel.CellType.*;

/**
* @Description:    Excel工具类
* @Author:         Joe
* @CreateDate:     2020/3/19 20:40
*/

@Slf4j
public class ExcelUtil {

    public static void exportExcel(HttpServletResponse response, ExcelDatas data) {
        log.info("导出解析开始,fileName:{}",data.getFileName());
        try {
            //实例化HSSFWorkbook
            XSSFWorkbook workbook = new XSSFWorkbook();
            //创建一个Excel表单,参数为sheet的名字
            XSSFSheet sheet = workbook.createSheet("sheet");
            //设置表头
            setTitle(workbook, sheet, data.getHead());
            //设置单元格并赋值
            setData(sheet, data.getDatas());
            //设置浏览器下载
            setBrowser(response, workbook, data.getFileName());
            log.info("导出解析成功!");
        } catch (Exception e) {
            log.info("导出解析失败!");
            e.printStackTrace();
        }
    }

    /**
     * 设置标题
     * @param workbook
     * @param sheet
     * @param str
     */
    private static void setTitle(XSSFWorkbook workbook, XSSFSheet sheet, String[] str) {
        try {
            XSSFRow row = sheet.createRow(0);
            //设置为居中加粗,格式化时间格式
            XSSFCellStyle style = workbook.createCellStyle();
            XSSFFont font = workbook.createFont();
            font.setBold(true);
            style.setFont(font);
            style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
            //创建表头名称
            XSSFCell cell;
            for (int j = 0; j < str.length; j++) {
                cell = row.createCell(j);
                cell.setCellValue(str[j]);
                cell.setCellStyle(style);
            }
        } catch (Exception e) {
            log.info("导出时设置表头失败!");
            e.printStackTrace();
        }
    }

    /**
     * 添加数据
     * @param sheet
     * @param data
     */
    private static void setData(XSSFSheet sheet, List<Teacher> data) {
        Teacher teacher=new Teacher();
        Field[] fields = teacher.getClass().getDeclaredFields();
        try{
            int rowNum = 1;
            for (int i = 0; i < data.size(); i++) {
                XSSFRow row = sheet.createRow(rowNum);
                teacher = data.get(i);
                for (int j = 0; j < fields.length; j++) {
                    if (j==0){
                        row.createCell(j).setCellValue(teacher.getId());
                    }
                    if (j==1){
                        row.createCell(j).setCellValue(teacher.getName());
                    }
                    if (j==2){
                        row.createCell(j).setCellValue(teacher.getAge());
                    }
                    if (j==3){
                        row.createCell(j).setCellValue(teacher.getSex());
                    }
                    if (j==4){
                        row.createCell(j).setCellValue(teacher.getSubject());
                    }

                }

                rowNum++;
            }
            log.info("表格赋值成功!");
        }catch (Exception e){
            log.info("表格赋值失败!");
            e.printStackTrace();
        }
    }

    /**
     * 使用浏览器下载
     * @param response
     * @param workbook
     * @param fileName
     */
    private static void setBrowser(HttpServletResponse response, XSSFWorkbook workbook, String fileName) {
        try {
            //清空response
            response.reset();
            //设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            //将excel写入到输出流中
            workbook.write(os);
            os.flush();
            os.close();
            log.info("设置浏览器下载成功!");
        } catch (Exception e) {
            log.info("设置浏览器下载失败!");
            e.printStackTrace();
        }

    }

    /**
     * 导入解析
     * @param
     * @return
     */
    public static List<Object[]> importExcel(InputStream inputStream, String fileName) {
        log.info("导入解析开始,fileName:{}",fileName);
        try {
            List<Object[]> list = new ArrayList<>();
            //InputStream inputStream = new FileInputStream(fileName);
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            //获取sheet的行数
            int rows = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rows; i++) {
                //过滤表头行
                if (i == 0) {
                    continue;
                }
                //获取当前行的数据
                Row row = sheet.getRow(i);
                Object[] objects = new Object[row.getPhysicalNumberOfCells()];
                int index = 0;
                for (Cell cell : row) {
                    if (cell.getCellType().equals(NUMERIC)) {
                        objects[index] = (int) cell.getNumericCellValue();
                    }
                    if (cell.getCellType().equals(STRING)) {
                        objects[index] = cell.getStringCellValue();
                    }
                    if (cell.getCellType().equals(BOOLEAN)) {
                        objects[index] = cell.getBooleanCellValue();
                    }
                    if (cell.getCellType().equals(ERROR)) {
                        objects[index] = cell.getErrorCellValue();
                    }
                    if (cell.getCellType().equals(BLANK)) {
                        objects[index] = " ";
                    }
                    if (cell.getCellType().equals(FORMULA)) {
                        objects[index] = cell.getCellFormula();
                    }
                    index++;
                }
                list.add(objects);
            }
            log.info("导入文件解析成功!");
            return list;
        }catch (Exception e){
            log.info("导入文件解析失败!");
            e.printStackTrace();
        }
        return null;
    }

}

5.在/resources/templates下新建excel.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Excel测试页面title>
head>
<body>

<h3>数据导入h3>
<br>
<hr/>
<form method="post" enctype="multipart/form-data" action="/importExcel">
    <p>
        导入文件<input type="file" name="file"/>
    p>
    <p>
        <input type="submit" value="开始导入"/>
    p>
form>
<br>
<h3>Excel导出表格测试页面h3>
<br>
<a href="/export">导出表格a>
<hr/>
body>
html>

6.创建一个Controller类ExcelController.java,进行数据导入、导出

package com.basic.hellorabbit.controller;

import com.basic.hellorabbit.entity.ExcelDatas;
import com.basic.hellorabbit.entity.Teacher;
import com.basic.hellorabbit.util.ExcelUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @Description:    Excel测试页面
* @Author:         Joe
* @CreateDate:     2020/3/20 17:15
*/
@Controller
public class ExcelController {

    /**
     * 跳转到Excel测试页面
     * @return
     */
    @RequestMapping(value = "/toexcel",method = RequestMethod.GET)
    public String toExcel(){
        return "excel";
    }

    /**
     * 数据导出
     * @param response
     */
    @RequestMapping(value = "/export",method = RequestMethod.GET)
    public void ExportExcel(HttpServletResponse response){
        List<Teacher> teachers = new ArrayList<>();
        teachers.add(new Teacher(1,"韩信",25,"男","刺客"));
        teachers.add(new Teacher(1,"钟无艳",25,"女","战士"));
        ExcelDatas excelDatas = new ExcelDatas();
        excelDatas.setFileName("teachers.xlsx");
        String[] strings = {"id","姓名","年纪","性别","科目"};
        excelDatas.setHead(strings);
        excelDatas.setDatas(teachers);
        ExcelUtil.exportExcel(response,excelDatas);
    }
    /**
     * 数据导入
     * @param file
     */
    @ResponseBody
    @RequestMapping(value = "/importExcel",method = RequestMethod.POST)
    public String importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String fileName = file.getName();
        List<Object[]> list = ExcelUtil.importExcel(inputStream,fileName);
        for (int i = 0; i < list.size(); i++) {
            Teacher teacher = new Teacher();
            teacher.setId((Integer)list.get(i)[0]);
            teacher.setName((String) list.get(i)[1]);
            teacher.setAge((Integer)list.get(i)[2]);
            teacher.setSex((String)list.get(i)[3]);
            teacher.setSubject((String) list.get(i)[4]);
            System.out.println(teacher.toString());
        }
        return "导入成功!";
    }
}

7.如图Excel表格
在这里插入图片描述

你可能感兴趣的:(常用代码块与笔记,poi,excel,spring,boot,封装)