java实现excel表格数据导入到数据库

所需依赖:

 
        
            org.apache.poi
            poi
            3.9
        
        
            org.apache.poi
            poi-ooxml
            3.9
        
        
            org.apache.poi
            poi-ooxml-schemas
            3.9
        

实现:
controller层

package com.personal.test.controller.importExcel;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.personal.test.common.domin.R;
import com.personal.test.service.ImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;

/**
 * @author linyh
 * @version 1.0
 * @email [email protected]
 * @date 2020/10/20 17:19
 */
@Controller
public class ImportController {

    @Autowired
    private ImportService importService;
    /**
     * Excel文件数据导入到数据库
     * @return
     */
    @PostMapping("/import")
    @ResponseBody
    public R importExcel(@RequestParam(value="file",required = false) MultipartFile file) throws IOException, ParseException, InvalidFormatException {
        return importService.readExcelFile(file);
    }
}

service层

package com.personal.test.service;

import com.personal.test.common.domin.R;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author linyh
 * @version 1.0
 * @email [email protected]
 * @date 2020/10/20 17:22
 */
public interface ImportService {
    R readExcelFile(MultipartFile file);
}

serviceImpl层

package com.personal.test.service.serviceImpl;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.personal.test.common.domin.R;
import com.personal.test.service.ImportService;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
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 org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

/**
 * @author linyh
 * @version 1.0
 * @email [email protected]
 * @date 2020/10/20 17:24
 */
@Service
public class ImportServiceImpl implements ImportService {

    @Override
    public R readExcelFile(MultipartFile file) {
        // 读取Excel里面的信息
        Workbook wb = null;
        try {
            wb = create(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        int rows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数
        int columns = sheet.getRow(0).getPhysicalNumberOfCells();
        // 遍历行(从1开始,去除Excel表头数据)
        for (int i = 1; i < rows; i++) {
            Row row = sheet.getRow(i);
            // 在某行的基础下,遍历该行所有列
            for (int i1 = 0; i1 < columns; i1++) {
                // 获取单元格
                Cell cell = row.getCell(i1);
                if(null != cell){
                    // 设置单元格类型,方便取值
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    // 获取单元格内容
                    String value = String.valueOf(cell.getRichStringCellValue());
                    // todo:将内容赋值到某个实体类进入sql插入操作(数据封装,再插入即可)
                }
            }
        }
        return R.success();
    }

    /**
     * 对HSSFWorkbook/XSSFWorkbook兼容处理
     * @param inp
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static Workbook create(InputStream inp) throws IOException, InvalidFormatException {
        if (!inp.markSupported()) {
            inp = new PushbackInputStream(inp, 8);
        }
        if (POIFSFileSystem.hasPOIFSHeader(inp)) {
            return new HSSFWorkbook(inp);
        }
        if (POIXMLDocument.hasOOXMLHeader(inp)) {
            try {
                return new XSSFWorkbook(OPCPackage.open(inp));
            } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
                e.printStackTrace();
            }
        }
        throw new IllegalArgumentException("你的excel版本目前poi解析不了");
    }
}

ps:如果你的Excel文档里面包含日期格式,代码里面获取的值为该日期距1900/01/01的天数,转换一下就好啦
// value是获取到的单元格内容
 String date =LocalDate.of(1900,1,1).plusDays(Long.parseLong(value)-2).toString();
 Date date = new SimpleDateFormat("yyyy-MM-dd").parse(value);

你可能感兴趣的:(java实现excel表格数据导入到数据库)