通过poi导入Excel表中数据

参考作为模板使用,视情况改动即可。

1.直接接收前台报文

接口请求:

public Object updateMeiTuanPayLog(@RequestParam(value = "file") MultipartFile file) throws ParmsException {
        JSONObject jsonObject = new JSONObject();
        try {
            InputStream in = null;
            if (file.isEmpty()){
                throw new Exception("该文件不存在");
            }
            in = file.getInputStream();
            jsonObject = payLogService.updateMeiTuanPayLog(in,file.getOriginalFilename());
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("flag",0);
            return success(jsonObject);
        }
        return success(jsonObject);
    }

业务层调用

  @Override
    public JSONObject updateMeiTuanPayLog(InputStream in, String originalFilename) throws Exception {
        JSONObject obj = new JSONObject();
        List<List<Object>> listByExcel = new LogReadExcelUtil().getListByExcel(in, originalFilename);
        in.close();
        List<H2PaymentLog> paymentLogs = new ArrayList<>();
        for (int i = 0; i < listByExcel.size(); i++){

            List<Object> objects = listByExcel.get(i);
            H2PaymentLog h2PaymentLog = new H2PaymentLog();
            if (objects.get(0) != null && !"".equals(objects.get(0))){
                h2PaymentLog.setPlPaymentno(objects.get(0).toString());
            }
        //...有几列循环几列就OK,具体业务不做赘述
        }

LogReadExcelUtil,这个工具类是对poi的具体操作。

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.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * create by zhangpk
 */
public class LogReadExcelUtil {
    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 IOException
     */
    public  List<List<Object>> getListByExcel(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;}
            boolean flag = false;
            int first = 0;
            if (i == 0){
                first = 1;//因为我这里是首行是表头,所以这样搞来着,可改为自己喜欢的方式
            }
            //遍历当前sheet中的所有行
            for (int j = first; j < sheet.getLastRowNum()+1;) {
                row = sheet.getRow(j);
                if(row==null){
                    sheet.shiftRows(j+1,sheet.getLastRowNum(),-1);
                    continue;
                }
                flag = false;
                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum() + 1; y++) {
                    cell = row.getCell(y);
                    if (cell == null){continue;}
                    if (cell.getCellType() != Cell.CELL_TYPE_BLANK){
                        flag = true;
                        li.add(this.getCellValue(cell));
                    }
                }
                if(flag){
                    j++;
                    list.add(li);
                    continue;
                }else{//如果是空白行(即可能没有数据,但是有一定格式)
                    if(j == sheet.getLastRowNum())//如果到了最后一行,直接将那一行remove掉
                        sheet.removeRow(row);
                    else//如果还没到最后一行,则数据往上移一行
                        sheet.shiftRows(j+1, sheet.getLastRowNum(),-1);
                }

            }
        }
        work.close();
        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)){
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }

    public  Object getCellValue(Cell cell){
        Object value = null;

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                value = cell.getNumericCellValue()*100;
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }



}

更新,工具类解决excel表中由于人为或者更方面原因导致的空数据读取问题。

由于业务需要,需要前台传来远程文件地址来生成流。

public Object updateMeiTuanPayLog(@RequestBody JSONObject obj) throws ParmsException, FileNotFoundException {
        checkParms(obj.getString("url"));
        String url = obj.getString("url");
        JSONObject jsonObject = new JSONObject();
        try {
            URL httpUrl = new URL(url);
            URLConnection urlConnection = httpUrl.openConnection();
            InputStream in = urlConnection.getInputStream();
            jsonObject = payLogService.updateMeiTuanPayLog(in,url);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("flag",0);
            return success(jsonObject);
        }
        return success(jsonObject);
    }

2.通过路径获取流信息。

 String path = "C:\\Users\\Zhang Peike\\Desktop\\sss.xlsx";
        FileInputStream is = new FileInputStream(path);
        String fileName = path.substring(path.lastIndexOf("/")+1);
        System.out.println(fileName);
        try {
            List<List<Object>> listByExcel = new LogReadExcelUtil().getListByExcel(is, fileName);
            System.out.println(listByExcel);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }

猜你喜欢

转载自blog.csdn.net/weixin_42140580/article/details/84996440