1、XSSFWorkbook生成模板以及解析模板


XSSFWorkbook生成模板以及解析模板

1、生成模板

只生成模板表頭的一列,跟據數據的類型同步到模板的格式,必錄單元格加*,時間格式化等,有長度、枚舉值的批注提示。

1.1新增一個VO對單元格數據格式進行定義

package com.ss.ifrs.datamgr.pojo.other.vo;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;

public class DmExcelCellVo {
    private XSSFCell hssfCell;
    private XSSFCellStyle hssfCellStyle;
    /**
     * 行
     */
    private Integer row;
    /**
     * 列
     */
    private Integer column;

    private Object value;

    private String columnCellType;

    public XSSFCellStyle getHssfCellStyle() {
        return hssfCellStyle;
    }

    public void setHssfCellStyle(XSSFCellStyle hssfCellStyle) {
        this.hssfCellStyle = hssfCellStyle;
    }

    /**
     * 合並單元格,行開始
     */
    private Integer mergerRowStart;

    /**
     * 合並單元格,行結束
     */
    private Integer mergerRowEnd;

    /**
     * 合並單元格,列開始
     */
    private Integer mergerColumnStart;

    /**
     * 合並單元格,列結束
     */
    private Integer mergerColumnEnd;

    /**
     * 增加批注
     */
    private String comment;

    /**
     * 字段長度
     */
    private String colLength;

    private String language;


    public DmExcelCellVo(XSSFCellStyle hssfCellStyle, Integer row, Integer column, Object value) {
        this.hssfCellStyle = hssfCellStyle;
        this.row = row;
        this.column = column;
        this.value = value;

    }

    public DmExcelCellVo(XSSFCellStyle hssfCellStyle, Integer row, Integer column, Object value, String columnCellType,String comment,String colLength,String language) {
        this.hssfCellStyle = hssfCellStyle;
        this.row = row;
        this.column = column;
        this.value = value;
        this.columnCellType = columnCellType;
        this.comment = comment;
        this.colLength = colLength;
        this.language = language;
    }

    public DmExcelCellVo(XSSFCellStyle hssfCellStyle, Integer row, Integer column, Object value, Integer mergerRowStart, Integer mergerRowEnd, Integer mergerColumnStart, Integer mergerColumnEnd) {
        this.hssfCellStyle = hssfCellStyle;
        this.row = row;
        this.column = column;
        this.value = value;
        this.mergerRowStart = mergerRowStart;
        this.mergerRowEnd = mergerRowEnd;
        this.mergerColumnStart = mergerColumnStart;
        this.mergerColumnEnd = mergerColumnEnd;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public DmExcelCellVo() {
    }

    public Integer getRow() {
        return row;
    }

    public void setRow(Integer row) {
        this.row = row;
    }

    public Integer getColumn() {
        return column;
    }

    public void setColumn(Integer column) {
        this.column = column;
    }

    public Integer getMergerRowStart() {
        return mergerRowStart;
    }

    public void setMergerRowStart(Integer mergerRowStart) {
        this.mergerRowStart = mergerRowStart;
    }

    public Integer getMergerRowEnd() {
        return mergerRowEnd;
    }

    public void setMergerRowEnd(Integer mergerRowEnd) {
        this.mergerRowEnd = mergerRowEnd;
    }

    public Integer getMergerColumnStart() {
        return mergerColumnStart;
    }

    public void setMergerColumnStart(Integer mergerColumnStart) {
        this.mergerColumnStart = mergerColumnStart;
    }

    public Integer getMergerColumnEnd() {
        return mergerColumnEnd;
    }

    public void setMergerColumnEnd(Integer mergerColumnEnd) {
        this.mergerColumnEnd = mergerColumnEnd;
    }

    public boolean isMergerCell() {
        if (ObjectUtils.isEmpty(mergerRowStart) || ObjectUtils.isEmpty(mergerRowEnd)
                || ObjectUtils.isEmpty(mergerColumnStart) || ObjectUtils.isEmpty(mergerColumnEnd)) {

            return false;
        } else {
            return true;
        }

    }

    public String getColumnCellType() {
        return columnCellType;
    }

    public void setColumnCellType(String columnCellType) {
        this.columnCellType = columnCellType;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getColLength() {
        return colLength;
    }

    public void setColLength(String colLength) {
        this.colLength = colLength;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
}

1.2、創建工具類對模板進行生成

創建模板:generateWorkbook

生成模板(只有表頭,沒有數據):generateExcelWithHeader

package com.ss.ifrs.datamgr.util;

import com.ss.ifrs.datamgr.pojo.other.vo.DmExcelCellVo;
import com.ss.platform.core.constant.DmConstant;
import com.ss.platform.core.constant.LocalesConstanst;
import com.ss.platform.core.util.StringUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * @author lgx
 * @date 2021/3/15
 * 生成excel文件
 */
public class ExcelGenerateUtils {

    private static XSSFWorkbook generateWorkbook(List<DmExcelCellVo> dmExcelCellVo) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Sheet1");
        XSSFCellStyle row1_style = createCellStyle(workbook, (short) 10, XSSFFont.COLOR_NORMAL, (short) 200, "宋體", HorizontalAlignment.CENTER);
        // 設置樣式
        XSSFCellStyle style = workbook.createCellStyle();
        // 設置樣式
//        style.setFillForegroundColor(IndexedColors.SKY_BLUE.index);
//        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        style.setBorderBottom(BorderStyle.THIN);
//        style.setBorderLeft(BorderStyle.THIN);
//        style.setBorderRight(BorderStyle.THIN);
//        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        //換行
        //style.setWrapText(true);
        // 生成一種字體
        XSSFFont font = workbook.createFont();
        // 設置字體
        font.setFontName("微軟雅黑");
        // 設置字體大小
        font.setFontHeightInPoints((short) 11);
        //設置字體加粗
        font.setBold(true);
        // 在樣式中引用這種字體
        style.setFont(font);

        generateTableHeader(workbook, sheet, style, dmExcelCellVo);

        return workbook;
    }

    public static void generateExcelWithHeader(HttpServletResponse response, List<DmExcelCellVo> dmExcelCellVo, String fileName) throws IOException {
        if (dmExcelCellVo.size() <= 0) {
            return;
        }

        XSSFWorkbook workbook = generateWorkbook(dmExcelCellVo);

        // 獲取輸出流
        OutputStream os = response.getOutputStream();
        // 重置輸出流
        response.reset();
        // 設定輸出文件頭
        response.setHeader("Content-disposition",
                "attachment; filename=" + new String(fileName.getBytes("GB2312"), "8859_1") + ".xlsx");
        // 定義輸出類型
        response.setContentType("application/msexcel");

        workbook.write(os);

        os.close();
    }

    public static void generateExcelWithHeader(List<DmExcelCellVo> dmExcelCellVo, String fileName, String filePath) throws IOException {
        if (CollectionUtils.isEmpty(dmExcelCellVo)) {
            throw new NoSuchElementException("Generate excel fail : not find template data");
        }

        XSSFWorkbook workbook = generateWorkbook(dmExcelCellVo);

        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        FileOutputStream fos = new FileOutputStream(filePath + "//" + fileName + ".xlsx");

        workbook.write(fos);

    }

    /**
     * 生成顏色
     *
     * @param workbook
     * @param xssfColor
     * @return
     */
    private static XSSFFont colorFont(XSSFWorkbook workbook, XSSFColor xssfColor) {
        XSSFFont font = workbook.createFont();
        // 設置字體
        font.setFontName("微軟雅黑");
        // 設置字體大小
        font.setFontHeightInPoints((short) 11);
        //設置字體加粗
        font.setBold(true);
        //設置顏色
        font.setColor(xssfColor);
        return font;
    }


    /**
     * 生成表格頭
     *
     * @param workbook
     * @param sheet
     * @param cellStyle
     * @param cell
     */
    private static void generateTableHeader(XSSFWorkbook workbook, XSSFSheet sheet, XSSFCellStyle cellStyle, List<DmExcelCellVo> cell) {
        XSSFFont font = cellStyle.getFont();
        XSSFFont redFont = colorFont(workbook, new XSSFColor(IndexedColors.RED, null));

        //創建繪圖對象
        XSSFDrawing patriarch = sheet.createDrawingPatriarch();

        for (int i = 0; i < cell.size(); i++) {
            XSSFCellStyle cellStyleFormat = workbook.createCellStyle();
            DmExcelCellVo dmExcelCellVo = cell.get(i);
            dmExcelCellVo.setHssfCellStyle(cellStyle);
            XSSFRow xssfRow = sheet.getRow(dmExcelCellVo.getRow());

            if (ObjectUtils.isEmpty(xssfRow)) {
                xssfRow = sheet.createRow(dmExcelCellVo.getRow());
            }

            sheet.setDefaultColumnStyle(dmExcelCellVo.getColumn(), cellStyleFormat);
            XSSFCell xssfCell = xssfRow.getCell(dmExcelCellVo.getColumn());
            if (xssfCell == null) {
                xssfCell = xssfRow.createCell(dmExcelCellVo.getColumn());
                xssfCell.setCellType(CellType.NUMERIC);
            }

            //長度
            String colLength = dmExcelCellVo.getColLength();
            //語言
            String language = dmExcelCellVo.getLanguage();

            //設置當前列的單元格格式
            XSSFDataFormat format = workbook.createDataFormat();
            String columnCellType = dmExcelCellVo.getColumnCellType();
            StringBuffer commentBuffer = new StringBuffer();

            if (DmConstant.DM_EXCEL_CELL_TYPE_STRING.equals(columnCellType)) {
                cellStyleFormat.setDataFormat(format.getFormat("@"));
                //增加批注
                if(LocalesConstanst.SYS_LANGUAGE_ZH.equals(language)){
                    commentBuffer.append("文本長度("+colLength+")\n");
                }else if (LocalesConstanst.SYS_LANGUAGE_TN.equals(language)){
                    commentBuffer.append("文本長度("+colLength+")\n");
                }else {
                    commentBuffer.append("Text Length("+colLength+")\n");
                }

            } else if (DmConstant.DM_EXCEL_CELL_TYPE_INTEGER.equals(columnCellType)) {
                //cellStyleFormat.setDataFormat(format.getFormat("0"));
                //增加批注
                if(LocalesConstanst.SYS_LANGUAGE_ZH.equals(language)){
                    commentBuffer.append( "數值長度("+colLength+")\n");
                }else if (LocalesConstanst.SYS_LANGUAGE_TN.equals(language)){
                    commentBuffer.append( "數值長度("+colLength+")\n");
                }else {
                    commentBuffer.append( "Number Length("+colLength+")\n");
                }
            } else if (DmConstant.DM_EXCEL_CELL_TYPE_DOUBLE.equals(columnCellType)) {
                StringBuffer stringBuffer = new StringBuffer("0.");
                String[] split = colLength.split(",");
                if(split.length > 1){
                    Integer precisionLength = Integer.valueOf(split[1]);
                    for (int j = 0; j < precisionLength; j++) {
                        stringBuffer.append("0");
                    }
                }
                //cellStyleFormat.setDataFormat(format.getFormat(stringBuffer.toString()));
                //增加批注
                if(LocalesConstanst.SYS_LANGUAGE_ZH.equals(language)){
                    commentBuffer.append( "數值長度("+colLength+")\n");
                }else if (LocalesConstanst.SYS_LANGUAGE_TN.equals(language)){
                    commentBuffer.append( "數值長度("+colLength+")\n");
                }else {
                    commentBuffer.append( "Number Length("+colLength+")\n");
                }
            } else if (DmConstant.DM_EXCEL_CELL_TYPE_DATE.equals(columnCellType)) {
                cellStyleFormat.setDataFormat(format.getFormat("m/d/yy"));
                //增加批注
                if(LocalesConstanst.SYS_LANGUAGE_ZH.equals(language)){
                    commentBuffer.append("日期格式('yyyy/MM/DD')\n");
                }else if (LocalesConstanst.SYS_LANGUAGE_TN.equals(language)){
                    commentBuffer.append("日期格式('yyyy/MM/DD')\n");
                }else {
                    commentBuffer.append("Date Format('yyyy/MM/DD')\n");
                }
            }

            //合並單元格
            if (dmExcelCellVo.isMergerCell()) {
                for (int j = dmExcelCellVo.getMergerRowStart(); j <= dmExcelCellVo.getMergerRowEnd(); j++) {
                    for (int k = dmExcelCellVo.getMergerColumnStart(); k <= dmExcelCellVo.getMergerColumnEnd(); k++) {
                        XSSFRow tempRow = sheet.getRow(j);
                        if (tempRow == null) {
                            tempRow = sheet.createRow(j);
                        }
                        XSSFCell tempCell = tempRow.getCell(k);
                        if (tempCell == null) {
                            tempCell = tempRow.createCell(k);
                        }
                        tempCell.setCellStyle(dmExcelCellVo.getHssfCellStyle());
                    }
                }
                sheet.addMergedRegion(new CellRangeAddress(dmExcelCellVo.getMergerRowStart(), dmExcelCellVo.getMergerRowEnd(), dmExcelCellVo.getMergerColumnStart(), dmExcelCellVo.getMergerColumnEnd()));
            }

            //設置單元格的值
            Object cellValue = dmExcelCellVo.getValue();
            if (cellValue instanceof Boolean) {
                xssfCell.setCellValue((Boolean) cellValue);
            } else if (cellValue instanceof Date) {
                xssfCell.setCellValue((Date) cellValue);
            } else if (cellValue instanceof String) {
                xssfCell.setCellValue((String) cellValue);
                String content = (String) cellValue;
                XSSFRichTextString xts = new XSSFRichTextString(content);
                int index = content.indexOf("*");
                if (index != -1) {
                    xts.applyFont(index, index + 1, redFont);
                    xts.applyFont(index + 1, content.length(), font);
                    /*String string = xts.getString();*/
                    xssfCell.setCellValue(xts);
                } else {
                    xssfCell.setCellValue((String) cellValue);
                }
            } else if (cellValue instanceof Double) {
                xssfCell.setCellValue((Double) cellValue);
            } else if (cellValue instanceof Calendar) {
                xssfCell.setCellValue((Calendar) cellValue);
            } else if (cellValue instanceof RichTextString) {
                xssfCell.setCellValue((RichTextString) cellValue);
            }

            //設置單元格的樣式
            if (ObjectUtils.isNotEmpty(dmExcelCellVo.getHssfCellStyle())) {
                xssfCell.setCellStyle(dmExcelCellVo.getHssfCellStyle());
            }
            //設置批注
            commentBuffer.append("\n");
            if(StringUtils.isNotEmpty(dmExcelCellVo.getComment())){
                commentBuffer.append(dmExcelCellVo.getComment());
            }
            xssfCell.setCellComment(createComment(patriarch,xssfCell,commentBuffer.toString()));

            // 根據字段長度自動調整列的寬度
            sheet.autoSizeColumn(dmExcelCellVo.getColumn(), true);
        }
    }

    /**
     *   生成批注對象,XSSFClientAnchor定義批注大小
     */
    public static XSSFComment createComment ( XSSFDrawing patriarch,XSSFCell xssfCell ,String commentValue){
        XSSFComment comment = patriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) xssfCell.getColumnIndex(), xssfCell.getRowIndex(), (short) xssfCell.getColumnIndex() + 5, xssfCell.getRowIndex() + 6));
        comment.setString(commentValue);
        return comment;
    }


    /**
     * 生成樣式
     *
     * @param workbook
     * @param fontHeightInPoints
     * @param color
     * @param fontHeight
     * @param fontName
     * @param align
     * @return
     */
    private static XSSFCellStyle createCellStyle(XSSFWorkbook workbook, short fontHeightInPoints, short color, short fontHeight, String fontName, HorizontalAlignment align) {
        XSSFFont font = workbook.createFont();
        // 表頭字體大小
        if (fontHeightInPoints != 0) {
            //font.setFontHeightInPoints((short) 6);
            font.setFontHeightInPoints(fontHeightInPoints);
        }

        //字體顏色
        if (color != 0) {
            //font.setColor(XSSFFont.COLOR_NORMAL);
            font.setColor(color);
        }

        if (fontHeight != 0) {
            // font.setFontHeight((short) 200);
            font.setFontHeight(fontHeight);
        }

        // 表頭字體名稱
        //font.setFontName("宋體");
        if (StringUtils.isNotEmpty(fontName)) {
            font.setFontName(fontName);
        }

        XSSFCellStyle cellStyle = workbook.createCellStyle();
        if (ObjectUtils.isNotEmpty(align)) {
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
        }

        cellStyle.setFont(font);
        return cellStyle;
    }
}

2、模板的解析

  1. 會對上傳模板進行解析,並對配置的長度、必錄字段進行校驗

  2. 對數值太大會導致校驗長度時生成的科學計數法,先對其轉化成字符來進行校驗,再通過字符轉為存儲的數值類型

    cellValue =  NumberToTextConverter.toText(cell.getNumericCellValue());
    
package com.ss.ifrs.datamgr.util;

import com.ss.ifrs.datamgr.pojo.other.vo.DmExcelParseVo;
import com.ss.platform.core.constant.CommonConstant;
import com.ss.platform.core.util.DataUtil;
import com.ss.platform.core.util.DateUtil;
import com.ss.platform.core.util.StringUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.el.parser.ParseException;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
import org.springframework.beans.BeanUtils;

import java.io.InputStream;
import java.math.BigDecimal;
import java.rmi.NotBoundException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author lgx
 */
public class ExcelImportUtils {

    public static List<List<DmExcelParseVo>> parseExcel(InputStream fs, List<DmExcelParseVo> parseList) throws Exception {
        List<List<DmExcelParseVo>> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(parseList)) {
            throw new NotBoundException("Upload template does not match the actual number of fields!");
        }
        //創建工作簿
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fs);
        //讀取第一個工作表
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
        //獲取最后一行的num,即總行數。此處從1開始計數
        int maxRow = sheet.getLastRowNum();
        
        int maxRol = sheet.getRow(0).getPhysicalNumberOfCells();
        int size = parseList.size();
        if (maxRol != size) {
            throw new ParseException("Parse Exception : Templates not up to date, Please download the latest template");
        }
        try {
            xssfRow : for (int row = 1; row <= maxRow; row++) {
                List<DmExcelParseVo> rowList = new ArrayList<>();
                //獲取最后單元格num,即總單元格數 ***注意:此處從1開始計數***
               /* int maxRol = sheet.getRow(row).getLastCellNum();
                int size = parseList.size();
                if (size != maxRol) {
                    throw new ParseException("Upload template does not match the actual number of fields!");
                }*/

                //空行處理
                XSSFRow xssfRow= sheet.getRow(row);
                boolean rowEmpty = ExcelImportUtils.isRowEmpty(xssfRow, maxRol);
                if(rowEmpty){
                    continue xssfRow;
                }

                int rol = 0;
                for (; rol < size; rol++) {
                    DmExcelParseVo parseVo = new DmExcelParseVo();
                    DmExcelParseVo dmParseExcelVo = new DmExcelParseVo();
                    BeanUtils.copyProperties(parseList.get(rol),dmParseExcelVo);

                    XSSFCell cell = xssfRow.getCell(rol);

                    //獲取當前表頭
                    XSSFCell cell1 = sheet.getRow(0).getCell(rol);
                    String cellHead = "";
                    if (cell1 != null && !CellType.BLANK.equals(cell1.getCellType())) {
                        cellHead = cell1.getStringCellValue();
                    }

                    //判斷是否必錄
                    if ("1".equals(dmParseExcelVo.getNeedIs()) && (cell == null || CellType.BLANK.equals(cell.getCellType()))) {
                        throw new ParseException("row : " + (row + 1) + ", column : " + (rol + 1) + ", " + cellHead + " Can't be empty");
                    }

                    String colType = dmParseExcelVo.getColType();
                    String colLength = dmParseExcelVo.getColLength();
                    String charsetName = "UTF-8";
                    if (ObjectUtils.isNotEmpty(cell)) {
                        if ("TIMESTAMP".equalsIgnoreCase(colType) || "DATE".equalsIgnoreCase(colType)) {
                            String dateStr;
                            // 不在正確的日期范圍1970/1/1 ~ 9999/12/31,其始終轉字符分別為25569、2958465
                            long startLong = new Long(25569);
                            long endLong = new Long(2958465);

                            try {
                                dmParseExcelVo.setColValue(cell.getDateCellValue());
                                // 重新設置單元格格式為String。如同excel日期格式設置文本格式
                                cell.setCellType(CellType.STRING);
                                dateStr = cell.getStringCellValue();
                                // 排除空或空字符情況
                                if(StringUtil.isNotEmpty(dateStr)){
                                    if(Long.parseLong(dateStr) - startLong < 0 ){
                                        // 單元格非法日期類型時,執行下方語句自動獲取catch部分異常
                                        dmParseExcelVo.setColValue(cell.getDateCellValue());
                                    }
                                    if(Long.parseLong(dateStr) - endLong > 0 ){
                                        // 單元格非法日期類型時,執行下方語句自動獲取catch部分異常
                                        dmParseExcelVo.setColValue(cell.getDateCellValue());
                                    }
                                }
                            } catch (IllegalStateException e) {
                                throw new ParseException("row : " + (row + 1) + ", column : " + (rol + 1) + ", " + cellHead + " value is not of type date!");
                            }
                        } else if ("NUMERIC".equalsIgnoreCase(colType) || "NUMBER".equalsIgnoreCase(colType) || "INTEGER".equalsIgnoreCase(colType)) {
                            double numericCellValue;
                            String cellValue;
                            try {
                                cellValue =  NumberToTextConverter.toText(cell.getNumericCellValue());
                                numericCellValue = Double.valueOf(cellValue);
                            } catch (IllegalStateException e) {
                                throw new ParseException("row : " + (row + 1) + ", column : " + (rol + 1) + ", " + cellHead + " value is not of type number!");
                            }

                            //長度校驗
                            if (StringUtils.isEmpty(colLength)) {
                                throw new ParseException("row : " + (row + 1) + ", column : " + (rol + 1) + ", " + cellHead + " length beyond 0 ");
                            }
                            //String cellValue = String.valueOf(numericCellValue);
                            String[] split = colLength.split(",");
                            //數字長度9,2
                            if (split.length > 1) {
                                Integer length = Integer.valueOf(split[0]);
                                Integer length2 = Integer.valueOf(split[1]);
                                int precisionLength = length - length2;
                                String[] split1 = cellValue.split("\\.");
                                if (split1.length > 1) {
                                    byte[] bytes = split1[0].getBytes(charsetName);
                                    byte[] bytes2 = split1[1].getBytes(charsetName);
                                    if (bytes.length > precisionLength || bytes2.length > length2) {
                                        throw new ParseException("row : " + (row + 1) + ", column : " + (rol + 1) + ", " + cellHead + " length beyond " + colLength);
                                    }
                                }
                            } else {
                                Integer length = Integer.valueOf(split[0]);
                                String[] split1 = cellValue.split("\\.");
                                if (split1.length > 0) {
                                    byte[] bytes = split1[0].getBytes(charsetName);
                                    if (bytes.length > length) {
                                        throw new ParseException("row : " + (row + 1) + ", column : " + (rol + 1) + ", " + cellHead + " length beyond " + length);
                                    }
                                }
                            }

                            dmParseExcelVo.setColValue(numericCellValue);
                        } else {
                            String stringCellValue;
                            try {
                                stringCellValue = cell.getStringCellValue();
                            } catch (IllegalStateException e) {
                                throw new ParseException("row : " + (row + 1) + ", column : " + (rol + 1) + ", " + cellHead + " value is not of type text!");
                            }
                            //長度校驗
                            if (StringUtils.isNotEmpty(stringCellValue)) {
                                stringCellValue = stringCellValue.trim();
                                byte[] bytes = stringCellValue.getBytes(charsetName);
                                Integer length = Integer.valueOf(colLength);
                                if (bytes.length > length) {
                                    throw new ParseException("row : " + (row + 1) + ", column : " + (rol + 1) + ", " + cellHead + " length beyond " + length);
                                }
                            }

                            dmParseExcelVo.setColValue(stringCellValue);
                        }
                    }
                    //處理單元格為空串問題
                    if (StringUtil.isEmpty(String.valueOf(dmParseExcelVo.getColValue()).trim())) {
                        dmParseExcelVo.setColValue(null);
                    }
                    BeanUtils.copyProperties(dmParseExcelVo, parseVo);
                    rowList.add(parseVo);
                }
                result.add(rowList);
            }
        }catch (ParseException e){
            throw e;
        } finally{
            if (xssfWorkbook != null) {
                xssfWorkbook.close();
            }
            if (fs != null) {
                fs.close();
            }
        }
        return result;
    }

    private static  boolean isRowEmpty(XSSFRow row,int headCell){
        if(row==null){
            return true;
        }
        int countCell = 0;
        for (int i = 0; i < headCell; i++) {
            XSSFCell cell = row.getCell(i);
            if(cell == null || CellType.BLANK.equals(cell.getCellType())){
                countCell++;
            }
        }
        if(countCell==headCell){
            return true;
        }
        return  false;
    }

}

isRowEmpty:對空行進行處理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM