文档章节

ExcleTransfer

Curry_M
 Curry_M
发布于 2017/04/07 15:30
字数 706
阅读 2
收藏 0
package com.pingan.common.transfer;

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

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.pingan.common.model.BaseEntity;

/**
 * @author chinwer
 * @created 2014-5-20
 */
public abstract class ExcelTransfer<T extends BaseEntity> {

    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
    public static final String NOT_EXCEL_FILE = " : Not the Excel file!";
    public static final String PROCESSING = "Processing...";
    public static final String EMPTY = "";
    public static final String POINT = ".";

    protected abstract T getModel();

    private List<String> parseErrorList = new ArrayList<String>();

    public String getParseErrorInfo() {
        if (!parseErrorList.isEmpty()) {
            return ArrayUtils.toString(parseErrorList, "\n");
        }
        return "";
    }

    /**
     * @return the parseErrorList
     */
    public List<String> getParseErrorList() {
        return parseErrorList;
    }

    /**
     * 读取xls或者xlsx文件
     * @param is excel文件输入流
     * @param startRow 开始行 传null值默认取1
     * @param endRow 结束行  传null值默认取现有数据行
     * @param startColumn 开始列
     * @param endColumn 结束列
     * @return 每行数据以list返回,每个元素对应一列
     * @throws Exception 
     */
    public List<T> readExcel(String fileName, InputStream is, Integer startRow, Integer endRow, Integer startColumn,
            Integer endColumn) throws Exception {
        if (is == null) {
            throw new Exception("is参数为必传");
        }
        if (startColumn == null || endColumn == null) {
            throw new Exception("startColumn和endColumn参数为必传");
        } else {
            String postfix = getPostfix(fileName);
            if (StringUtils.isNotBlank(postfix)) {
                if (OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
                    return readXls(is, startRow, endRow, startColumn, endColumn);
                } else if (OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
                    return readXlsx(is, startRow, endRow, startColumn, endColumn);
                }
            } else {
                System.out.println(fileName + NOT_EXCEL_FILE);
            }
        }
        return null;
    }

    /**
     * Read the Excel 2010
     * @param is of the excel file
     * @return
     * @throws IOException
     */
    public List<T> readXlsx(InputStream is, Integer startRow, Integer endRow, Integer startColumn, Integer endColumn)
            throws IOException {
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        List<T> retlist = new ArrayList<T>();
        for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
            if (xssfSheet == null) {
                continue;
            }
            if (startRow == null)
                startRow = 1;
            if (endRow == null)
                endRow = xssfSheet.getLastRowNum() + 1;
            for (int rowNum = startRow - 1; rowNum < endRow; rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                if (xssfRow != null) {
                    List<String> errorList = new ArrayList<String>();
                    T model = getModel();
                    for (int colNum = startColumn; colNum <= endColumn; colNum++) {
                        try {
                            setCellValue(model, xssfRow, colNum);
                        } catch (Exception e) {
                            errorList.add(String.valueOf(colNum));
                        }
                    }
                    if (!errorList.isEmpty()) {
                        parseErrorList.add("第" + String.valueOf(xssfRow.getRowNum() + 1) + "行的第"
                                + ArrayUtils.toString(errorList, ",") + "列存在格式错误!");
                    } else if (retlist.contains(model)) {
                        parseErrorList.add("第" + String.valueOf(xssfRow.getRowNum() + 1) + "行的数据重复!");
                    } else {
                        model.setRowNum(String.valueOf(xssfRow.getRowNum() + 1));
                        retlist.add(model);
                    }
                }
            }
            break;
        }
        return retlist;
    }

    /**
     * Read the Excel 2003-2007
     * @param is of the Excel
     * @return
     * @throws IOException
     */
    public List<T> readXls(InputStream is, Integer startRow, Integer endRow, Integer startColumn, Integer endColumn)
            throws IOException {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        List<T> retlist = new ArrayList<T>();
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
            System.out.println(numSheet);
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            if (startRow == null)
                startRow = 1;
            if (endRow == null)
                endRow = hssfSheet.getLastRowNum() + 1;
            for (int rowNum = startRow - 1; rowNum < endRow; rowNum++) {
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    List<String> errorList = new ArrayList<String>();
                    T model = getModel();
                    for (int colNum = startColumn; colNum <= endColumn; colNum++) {
                        try {
                            setCellValue(model, hssfRow, colNum);
                        } catch (Exception e) {
                            errorList.add(String.valueOf(colNum));
                        }
                    }
                    if (!errorList.isEmpty()) {
                        parseErrorList.add("第" + String.valueOf(hssfRow.getRowNum() + 1) + "行的第"
                                + ArrayUtils.toString(errorList, ",") + "列存在格式错误!");
                    } else if (retlist.contains(model)) {
                        parseErrorList.add("第" + String.valueOf(hssfRow.getRowNum() + 1) + "行的数据重复!");
                    } else {
                        model.setRowNum(String.valueOf(hssfRow.getRowNum() + 1));
                        retlist.add(model);
                    }
                }
            }
            break;
        }
        return retlist;
    }

    @SuppressWarnings("static-access")
    protected String getValue(Cell cell, DecimalFormat df) {
        if (cell == null) {
            return EMPTY;
        }
        if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
            return df.format(cell.getNumericCellValue());
        } else {
            return String.valueOf(cell.getStringCellValue());
        }
    }

    private static String getPostfix(String path) {
        if (path == null || StringUtils.isEmpty(path.trim())) {
            return EMPTY;
        }
        if (path.contains(POINT)) {
            return path.substring(path.lastIndexOf(POINT) + 1, path.length());
        }
        return EMPTY;
    }

    /**
     * 设置每个单元格对应模型的属性<br>
     * (主要注意一下对存数字的单元格和即可能存字符又可能存数字的单元格的格式化)
     * @param model
     * @param row
     * @param colNum
     */
    protected abstract void setCellValue(T model, Row row, int colNum) throws Exception;
}

 

© 著作权归作者所有

共有 人打赏支持
上一篇: DateUtils
下一篇: 枚举
Curry_M
粉丝 1
博文 85
码字总数 83163
作品 0
浦东
程序员
私信 提问

暂无文章

聊聊flink的FsStateBackend

序 本文主要研究一下flink的FsStateBackend StateBackend flink-runtime_2.11-1.7.0-sources.jar!/org/apache/flink/runtime/state/StateBackend.java @PublicEvolvingpublic interface Sta......

go4it
25分钟前
1
0
webpack配置proxyTable时pathRewrite无效的解决方法

webpack配置接口地址代理 在项目开发中,接口联调的时候一般都是同域名下,且不存在跨域的情况下进行接口联调,但是当我们在本地启动服务器后,比如本地开发服务下是 http://localhost:8080 ...

前端小攻略
26分钟前
1
0
安装jenkins

1.下载 wget https://mirrors.tuna.tsinghua.edu.cn/jenkins/war/2.155/jenkins.war 2.后续操作和 dubbo 安装类似: (1)复制一份空白的tomcat,重命名为:jenkins-tomcat (2)war包放入t...

狼王黄师傅
34分钟前
2
0
zookeeper配置与使用

一.登录官网下载 不要带后缀的,那是公侧版本,下稳定版,比如3.4.9 二.安装与使用 解压后bin里是启动程序 配置文件:在conf下 复制zoo_sample.cfg改名为为zoo.cfg,打开zoo修改文件 临时数据保存...

小兵胖胖
58分钟前
3
0
spring源码阅读笔记(一)

ClassPathXmlApplicationContext 与 FileSystemXmlApplicationContext 用了这么久的框架,是时候搞一下源码了,一般最初接触spring 从以下步骤开始 创建一个bean类 并创建 ooxx.xml之类的spr...

NotFound403
今天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部