Springboot整合poi实现Excel导入导出到数据库

Springboot整合poi实现Excel导入导出到数据库

引入依赖


 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.8</version>
        </dependency>

Excel导入数据并解析到数据库

  1. controller层
    @ApiOperation("导入execl")
    @PostMapping("/UploadExcel")
    public ResponseWrapper ajaxUploadExcel(@RequestParam(value="excelFile",required = false) MultipartFile excelFile) throws ParseException {
        ResponseWrapper wrapper = recordService.UploadExcel(excelFile);
        return wrapper;
    }
  1. service层
public ResponseWrapper UploadExcel(MultipartFile file) throws ParseException {
        if (file.isEmpty()) {
            try {
                throw new Exception("文件不存在!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InputStream in = null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<List<Object>> listob = null;
        try {
            listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
            //          System.out.println("listob触发了"+listob);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
        for (int i = 0; i < listob.size(); i++) {
            List<Object> lo = listob.get(i);
            Record vo = new Record();
            Record j = null;

            //这里是主键验证,根据实际需要添加,可要可不要,加上之后,可以对现有数据进行批量修改和导入
            try {
                j = recordMapper.selectByPrimaryKey(Integer.valueOf(String.valueOf(lo.get(0))));
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
            }
            if (j == null) {
//                假如id为空则表示没有这条数据,创建这条数据
                vo.setId(Integer.valueOf(String.valueOf(lo.get(0))));
                vo.setContent(String.valueOf(lo.get(1)));
                vo.setNumber(String.valueOf(lo.get(2)));
                vo.setDeadline(String.valueOf(lo.get(3)));
                vo.setCompany(String.valueOf(lo.get(4)));
                vo.setWeeks(String.valueOf(lo.get(5)));
                addRecord(vo);
            } else {
//                如果这条数据存在则调用修改方法,修改这条数据
                vo.setId(Integer.valueOf(String.valueOf(lo.get(0))));
                vo.setContent(String.valueOf(lo.get(1)));
                vo.setNumber(String.valueOf(lo.get(2)));
                vo.setDeadline(String.valueOf(lo.get(3)));
                vo.setCompany(String.valueOf(lo.get(4)));
                vo.setWeeks(String.valueOf(lo.get(5)));
                updateRecord(vo);
            }
        }
        return ResponseWrapper.markSuccess(null);
    }

数据将数据库的数据导出到excel

  1. contoller层
    @ApiOperation("导出excel")
    @GetMapping("/excel")
    public void excel( HttpServletResponse response)throws IOException {
        recordService.excel(response);
        return;
    }
  1. service层
public void excel(HttpServletResponse response)throws IOException{
        //确定编码的格式
        response.setCharacterEncoding("UTF-8");
        //获取导出的数据
        List<Admin> list = adminMapper.findAllAdmin();
        //创建excel文件
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建sheet页
        XSSFSheet sheet = wb.createSheet("学生信息表");
        //创建标题行
        XSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("ID");
        titleRow.createCell(1).setCellValue("姓名");
        titleRow.createCell(2).setCellValue("密码");
        titleRow.createCell(3).setCellValue("角色");
        titleRow.createCell(4).setCellValue("时间");
        //遍历将数据放到excel列中
        for (Admin student : list) {
            XSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(student.getAid());
            dataRow.createCell(1).setCellValue(student.getUsername());
            dataRow.createCell(2).setCellValue(student.getPassword());
            dataRow.createCell(3).setCellValue(student.getSrole());
            
           //由于时间数据库格式是date,所以要将时间格式进行转换
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            String time = format.format(student.getTime());
            dataRow.createCell(4).setCellValue(time);
        
        // 设置下载时客户端Excel的名称   (上面注释的改进版本,上面的中文不支持)
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                //该版本为2007-的版本
                + new String("名单".getBytes("UTF-8"),"iso-8859-1")
                + ".xlsx");
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }

工具类(导入导出都要调用)


package com.zgqk.method;


import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Excel工具类
 */
public class ExcelUtils {
    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel

    /**
     * 描述:获取IO流中的数据,组装成List<List<Object>>对象
     * @param in,fileName
     * @return
     * @throws
     */
    public  List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception{
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = this.getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("创建Excel工作薄为空!");
        }
        Sheet sheet = null;  //页数
        Row row = null;  //行数
        Cell cell = null;  //列数

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if(row==null||row.getFirstCellNum()==j){continue;}

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    li.add(this.getValue(cell));
                }
                list.add(li);
            }
        }
        return list;
    }
    /**
     * 描述:根据文件后缀,自适应上传文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003L.equals(fileType)){
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){
            //2003版运用HSS协议,2007运用XSS协议
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }
    /**
     * 描述:对表格中数值进行格式化
     * @param cell
     * @return
     */
    //解决excel类型问题,获得数值
    public  String getValue(Cell cell) {
        String value = "";
        if(null==cell){
            return value;
        }
        //poi.jar高版本中其中的常量的名称会改变
        switch (cell.getCellType()) {
            //数值型
            case Cell.CELL_TYPE_NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //如果是date类型则 ,获取该cell的date值
                    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    value = format.format(date);
                }else {// 纯数字
                    BigDecimal big=new BigDecimal(cell.getNumericCellValue());
                    value = big.toString();
                    //解决1234.0  去掉后面的.0
                    if(null!=value&&!"".equals(value.trim())){
                        String[] item = value.split("[.]");
                        if(1<item.length&&"0".equals(item[1])){
                            value=item[0];
                        }
                    }
                }
                break;
            //字符串类型
            case Cell.CELL_TYPE_STRING:
                value = cell.getStringCellValue();
                break;
            // 公式类型
            case Cell.CELL_TYPE_FORMULA:
                //读公式计算值
                value = String.valueOf(cell.getNumericCellValue());
                if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
                    value = cell.getStringCellValue();
                }
                break;
            // 布尔类型
            case Cell.CELL_TYPE_BOOLEAN:
                value = " "+ cell.getBooleanCellValue();
                break;
            default:
                value = cell.getStringCellValue();
        }
        if("null".endsWith(value.trim())){
            value="";
        }
        return value;
    }
}

上一篇:GPS(Global Positioning System)全球定位系统


下一篇:Graham扫描法