文档章节

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;
}

 

© 著作权归作者所有

共有 人打赏支持
Curry_M
粉丝 1
博文 88
码字总数 84728
作品 0
浦东
程序员

暂无文章

[雪峰磁针石博客]python3快速入门教程1 turtle绘图-2函数

菲波那契序列: >>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1>>> while b < 10:... print(b)... a, b = b, a+b...112......

python测试开发人工智能安全
今天
0
0
java环境变量配置最正确的方式

原贴:https://blog.csdn.net/qq_40007997/article/details/79784711,十分详细,亲测有效

kitty1116
今天
0
0
49.Nginx防盗链 访问控制 解析php相关 代理服务器

12.13 Nginx防盗链 12.14 Nginx访问控制 12.15 Nginx解析php相关配置(502的问题) 12.16 Nginx代理 扩展 502问题汇总 http://ask.apelearn.com/question/9109 location优先级 http://blog....

王鑫linux
今天
1
0
Nginx防盗链、访问控制、解析php相关配置、Nginx代理

一、Nginx防盗链 1. 编辑虚拟主机配置文件 vim /usr/local/nginx/conf/vhost/test.com.conf 2. 在配置文件中添加如下的内容 { expires 7d; valid_referers none blocked server_names *.tes......

芬野de博客
今天
0
0
spring EL 和资源调用

资源调用 import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.core.io.Resource;......

Canaan_
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部