Simple upload excel file and add data to the database

1. The introduction of pom file (error prevention remain the same version of each jar package)

    <dependency>  
        <groupId>org.apache.poi</groupId>  
        <artifactId>poi-ooxml</artifactId>  
        <version>3.17</version>  
    </dependency>  
    <dependency>  
        <groupId>org.apache.poi</groupId>  
        <artifactId>poi-ooxml-schemas</artifactId>  
        <version></3.17version>  
    </dependency>  
    <dependency>  
        <groupId>org.apache.poi</groupId>  
        <artifactId>poi</artifactId>  
        <version>3.17</version>  
    </dependency> 

2. Import files Tools

package com.yami.shop.admin.config;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ImportExcel {
    // abc.xls
    public static boolean isXls(String fileName){
        // (?i)忽略大小写
        if(fileName.matches("^.+\\.(?i)(xls)$")){
            return true;
        }else if(fileName.matches("^.+\\.(?i)(xlsx)$")){
            return false;
        } The else {
             the throw  new new a RuntimeException ( "wrong format" );
        }
    }
    public static List<Map<String, Object>> readExcel(String fileName, InputStream inputStream) throws Exception{
        boolean ret = isXls(fileName);
        Workbook the Workbook = null ;
         // create different objects in accordance with the suffix 
        IF (RET) {
            workbook = new HSSFWorkbook(inputStream);
        }else{
            workbook = new XSSFWorkbook(inputStream);
        }
        Sheet sheet = workbook.getSheetAt(0);
        // 得到标题行
        Row titleRow = sheet.getRow(0);
        int lastRowNum = sheet.getLastRowNum();
        int lastCellNum = titleRow.getLastCellNum();
        List<Map<String, Object>> list = new ArrayList<>();
        for(int i = 1; i <= lastRowNum; i++ ){
            Map<String, Object> map = new HashMap<>();
            Row row = sheet.getRow(i);
            for(int j = 0; j < lastCellNum; j++){
                // 得到列名
                String key = titleRow.getCell(j).getStringCellValue();
                Cell cell = row.getCell(j);
                cell.setCellType (CellType.STRING);

                map.put(key, cell.getStringCellValue());
            }
            list.add(map);
        }
        workbook.close();
        return list;
    }
}

3.controller control layer

package com.yami.shop.admin.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yami.shop.admin.config.ImportExcel;
import com.yami.shop.bean.model.TzJobSet;
import com.yami.shop.common.bean.Result;
import com.yami.shop.service.ITzJobSetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/staff")
public class TestExcel {

    @Autowired
    private ITzJobSetService tzJobSetService;

    @PostMapping("/import")
    @Transactional
    public Boolean importExcel(@RequestParam MultipartFile mFile){
        Result result =new Result();
        try {
            FileName String = mFile.getOriginalFilename ();
             // get the input stream uploaded files 
            InputStream inputStream = mFile.getInputStream ();
             // call the class method tools, read the data from excel files 
            List <Map <String, Object >> sourceList = ImportExcel.readExcel (fileName, inputStream);

            // object json format string into first, and then converted to List <TzJobSet> Object TzJobSet: entity class corresponding to the table 
            ObjectMapper objMapper = new new ObjectMapper ();
            String infos = objMapper.writeValueAsString(sourceList);

            // JSON an object string rotation 
            List <TzJobSet> List = objMapper.readValue (the infos, new new typereference <List <TzJobSet >> () {});

            // The method used to add bulk items mybatis-pius frame saveBatch batch is added mybatis-pius carrying 
            Boolean B = tzJobSetService.saveBatch (List);
             return B;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
}

 

Guess you like

Origin www.cnblogs.com/livedian/p/11803381.html