[Java] [46] to import Excel database

Preface:

Business Scenario: users Excel spreadsheet, clicking on the page "Import button", the system reads the data in Excel, corresponding to the stored database

Note:

1, currently only introduced simple Excel table, not merged cells, can only read a single page sheet

2, the method used in the entity class specific business scenario, it is not very strong applicability, to use the words of another scene, also you need to modify the code. But also it has a certain reference resistance, so the first record. My subsequent idea is: field name in tools (ReadExcelUtil) introduced in accordance Excel header to be processed is determined, and then makes up the data format json, spread Service layer, do the processing. After the update again // TODO

3, jar package with: POI

text:

html:

<div>
    <span><input type="file" id="upfile" name="upfile" placeholder=""/></span>
    <button onclick="importExp();">导入</button>
    <span>格式:.xls</span>
</div>

JS:

function importExp() {
    var name = $("#upfile").val();
    var file =  $("#upfile")[0].files[0];
    // ajax...
}

Java:

Controller layer

@ApiOperation(value = "导入Excel")
@RequestMapping(value="excel/import", method = RequestMethod.POST)
public void importExcel(MultipartFile file) {
    return this.theService.importExcel(file);
}

Service Layer

public  void importExcel (MultipartFile File) {
     IF (file.isEmpty ()) {
         // Please select the Excel file. Whether the error information is returned to the front end, as the case may be. 
        return ; 
    } 

    the Result ReadResult = ReadExcelUtil.readExcel (File);   // the Result encapsulates the return value is the class, the entity class corresponding to 

    IF (! readResult.getCode () = 0 ) { 
         // Error: readResult.msg 
        return ; 
    } 
    List <Award> List = (List <Award>) readResult.getData (); // Award database table corresponding to the entity class 

    // after obtaining the list, insert into the database ... 
}

Tools:

ReadExcelUtil

package com.bf.base.utils;

import com.bf.base.entity.DripAward;
import com.bf.base.params.Result;
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;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ReadExcelUtil {

    /**
     * 读取 单页sheet,返回一个集合
     * @return
     */
    public static Result<?> readDripAwardExcel(MultipartFile file) {
        Result result = new Result<>();
        InputStream is = null;
        Workbook wb = null;
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

        try {
            is = file.getInputStream();

            if (fileType.equals("xls")) {
                wb = new HSSFWorkbook(is);
            } else if (fileType.equals("xlsx")) {
                wb = new XSSFWorkbook(is);
            } else {
                return new Result<>(Result.FAIL, "读取的不是excel文件", null, null);
            }

            int sheetSize = wb.getNumberOfSheets();//有多少sheet页
            if(sheetSize >= 2) {
                 Return  new new the Result <> (Result.FAIL, "Please check the number of pages Excel", null , null ); 
            } 

            Sheet Sheet = wb.getSheetAt (0 ); 
            Result = sheetData2List (Sheet); // key, sheet table set of data is transferred 

        } the catch (a FileNotFoundException E) { 
            e.printStackTrace (); 
        } the catch (IOException E) { 
            e.printStackTrace (); 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 

        return Result; 
    }

    //获取数据
    private static Result sheetData2List(Sheet sheet) {
        Result result = new Result<>();
        List<Award> awards = new ArrayList<>();
        int CELL_SIZE = 3; //excel固定三列(编码、金额)       
        int rowSize = sheet.getLastRowNum() + 1;

        for (int j = 0; j < rowSize; j++) { //读取每一行
            Row row = sheet.getRow(j);
            if (row == null) {
                continue;
            }

             row.getCell (K);IF (row.getLastCellNum () =! cell_size) { 
                result.setCode ( 2 ); 
                result.setMsg ( "first" + j + "abnormal data line, please check and then upload!" );
                 return Result; 
            } 

            IF (J 0 == ) {
                 Continue ; 
            } the else { 
                DripAward rowObj = new new DripAward ();
                 for ( int K = 0; K <cell_size; K ++) { // the data acquisition column 
                    the Cell Cell = 
                    String value = getCellFormatValue(cell);
                    switch (k) {
                        case 0:
                            rowObj.setCode(AESUtil.encrypt(value));
                            break;
                        case 1:
                            rowObj.setAmount(Double.parseDouble(value));
                            break;
                        case 2:
                            rowObj.setClassify(Integer.parseInt(value));
                            break;
                        default:
                            break;
                    }
                }
                awards.add(rowObj);
            }            
        }

        result.setCode(0);
        result.setData(awards);
        return result;
    }

    //获取列的数据
    private static String getCellFormatValue(Cell cell) {
        String cellvalue = "";
        if (cell != null) {
            CellType cellType = cell.getCellTypeEnum();
            switch (cellType) {
                case NUMERIC: {
                    if(String.valueOf(cell.getNumericCellValue()).indexOf("E") == -1){
                        cellvalue =  String.valueOf(cell.getNumericCellValue());
                    }else {
                        cellvalue =  new DecimalFormat("#").format(cell.getNumericCellValue());
                    }
                    break;
                }
                case STRING:
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:
                    cellvalue = "-";
            }
        }

        return cellvalue;
    }
}

other:

Result (class encapsulates the return value, corresponding to the entity class)

Package com.bf.base.params; 

Import org.apache.commons.lang.StringUtils; 

/ ** 
 * unified format data passed distal 
 * code = 0, the call was successful 
 * all remaining code call interface represents abnormality, the abnormality when, indicate exception code, and gives msg detail and annotation, the synchronization file 
 * / 
public  class the Result <T> { 
    
    Private  int code; // status return code 
    
    Private String msg; // return code description 
    
    Private String detail; // error detailed description or return processing program code corresponding 
    
    Private T data; // returns the data body 

    public  static  Final  int FAIL = -1 ; 

    public  static  Final int SUCCESS = 0;

    @Override
    public String toString() {
        return "Result [code=" + code + ", msg=" + msg + ", detail=" + detail + ", data=" + data + "]";
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
    
}

Award (based entity corresponding database table)

public class Award {
    private String code;

    private Double amount;

    private int classify;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public int getClassify() {
        return classify;
    }

    public void setClassify(int classify) {
        this.classify = classify;
    }
}

 

Guess you like

Origin www.cnblogs.com/huashengweilong/p/11363014.html