자바 엑셀 파일 조작

79745 단어 poiexcel
서비스 인터페이스 클래스
package com.deppon.tps.module.aboutexcel.server.poidlexcel.service;

import java.io.ByteArrayOutputStream;
import java.io.File;

import javax.servlet.http.HttpServletResponse;

import com.deppon.tps.module.aboutexcel.server.shared.domain.AnalysisFileEntity;
import com.deppon.tps.module.aboutexcel.server.shared.domain.AnalysisResponseEntity;


public interface IPOIdwExcelUtilsService {

    /**
     *          ,  ,       
     * @param entity
     * @return
     */
    public AnalysisResponseEntity importFileData(AnalysisFileEntity entity);


    /**
     *      ,   ,     excel  
     * @param title
     * @param entity
     * @return
     */
    public ByteArrayOutputStream exportExcel(String title,AnalysisResponseEntity entity);

    /**
     *     ,   ,     excel  
     * @param title
     * @param entity
     * @return
     */
    public ByteArrayOutputStream exportExcel(File file,AnalysisResponseEntity entity);

    /**
     *     ,     excel  ,    excel  
     * @param file
     * @param entity
     * @return
     */
    public String createExcel(File file,AnalysisResponseEntity entity);

    /**
     *   excel
     * @param path
     * @param response
     */
    public void download(String path, HttpServletResponse response);
}

서비스 구현 클래스
package com.deppon.tps.module.aboutexcel.server.poidlexcel.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.annotation.XmlElement;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
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 org.sonatype.aether.util.StringUtils;

import com.deppon.foss.framework.exception.BusinessException;
import com.deppon.tps.module.aboutexcel.server.poidlexcel.service.IPOIdwExcelUtilsService;
import com.deppon.tps.module.aboutexcel.server.shared.domain.AnalysisFileEntity;
import com.deppon.tps.module.aboutexcel.server.shared.domain.AnalysisResponseEntity;
import com.esafenet.dll.FileDlpUtil;

public class POIdwExcelUtlsServiceImpl implements IPOIdwExcelUtilsService {
    Logger log = Logger.getLogger(POIdwExcelUtlsServiceImpl.class);
    //sheet0         
    public static int SHEET_START_ROW_NUMBER = 0;
    //sheet0         
    public static int SHEET_START_COLUMN_NUMBER = 0;

    public static final int SHEET_LIMIT_ROW_NUMBER = 5000;

    /**
     *       
     * @param entity
     * @return
     */
    public AnalysisResponseEntity importFileData(AnalysisFileEntity entity){

        final File historyfile = entity.getFile();
        final File file = decryptFile(historyfile);
        entity.setFile(file);
        log.info("      ,"+file.getName());
        //          
        judgeFile(file);
        //       
        AnalysisResponseEntity responseentity = analysisFile(entity);

                if(historyfile.exists()){
                    historyfile.delete();   
                }
                if(file.exists()){
                    file.delete();  
                }

        return responseentity;
    }

    private File decryptFile(File file){
        String filepath = file.getAbsolutePath().substring(0,(int)file.getAbsoluteFile().toString().length()-file.getName().length());
        String filename = file.getName().substring(0, file.getName().indexOf("."))+"_UN"+file.getName().substring(file.getName().indexOf("."));
        File copyfile = new File(filepath+filename);

        boolean copysuccess = FileDlpUtil.decryptFile(file.getAbsolutePath(),filepath+filename);
        if(copysuccess){
            return copyfile;    
        }
        return null;
    }

    /**
     *           
     * @param file
     */
    public void judgeFile(File file){
        judegFileNull(file);
        //        
        judegFileSuffix(file);
        //      
        judgeFilelength(file);
        //      
        judegFreeMemory(file);
    }

    public void judegFileNull(File file){
        if(null == file || file.length()<=0){
            log.error("    !");
            throw new BusinessException("    !");
        }
    } 

    /**
     *         
     * @param file
     */
    public void judegFileSuffix(File file){
        String filename = file.getName();
        String sufffilename = "";
        if ((filename == null) ||((filename != null)&& (filename.length() <= 0))) {
            log.error("    :"+file.getName()+"     ");
            throw new BusinessException("       ,     ");
        }

        int dot = filename.lastIndexOf('.'); 
        if ((dot >-1) && (dot < (filename.length()))) { 
            sufffilename =   filename.substring(dot+1); 
            if(!"xls".equalsIgnoreCase(sufffilename) &&
               !"xlsx".equalsIgnoreCase(sufffilename)&&
               !"xlsm".equalsIgnoreCase(sufffilename)){
                log.error("  :"+file.getName()+"     ");
                throw new BusinessException("       ,     ");
            }
        } 
    }

    /**
     *       
     * @param file
     */
    public void judgeFilelength(File file){
        long length = file.length();
        //         3M
        if(length>3*1024*1024){
            log.error("  :"+file.getName()+"  ,"+file.length());
            throw new BusinessException("    ,     ");
        }
    }

    /**
     *       
     * @param file
     */
    public void judegFreeMemory(File file){
        long freememory = Runtime.getRuntime().freeMemory();
        //        3M    
        if(freememory < 3*1024*1024){
            log.error("  :"+file.getName()+"   ,    ");
            throw new BusinessException("    ,     !");
        }
    }


    /**
     *        
     * @param entity
     */
    public AnalysisResponseEntity analysisFile(AnalysisFileEntity entity){
        AnalysisResponseEntity responseentity = new AnalysisResponseEntity();
        //        
        XSSFWorkbook workbook = null;
        //       class  --  
        Field[] columnClassNamez = null;
        //    --  
        String[] columnNamez = null; 
        // excel          
        List list = new LinkedList();
        // excel          
        List errorlist = new LinkedList();
        // excel          
        List errorMessagelist = new LinkedList();
        //  sheet    
        boolean readover = false;
        File file = entity.getFile();

        try {
//          workbook = new HSSFWorkbook(new FileInputStream(file));
            workbook = new XSSFWorkbook(new FileInputStream(file));
        } catch (IOException e) {
            log.error("  "+file.getName()+"  ,    :"+e.getMessage());
            throw new BusinessException(e.getMessage());
        }
        //  excel     sheet
//      HSSFSheet sheet = workbook.getSheetAt(0);
        XSSFSheet sheet = workbook.getSheetAt(0);
        SHEET_START_ROW_NUMBER = sheet.getFirstRowNum();
        SHEET_START_COLUMN_NUMBER = sheet.getRow(SHEET_START_ROW_NUMBER).getFirstCellNum();
        //       
        if(sheet.getLastRowNum()>SHEET_LIMIT_ROW_NUMBER){
            log.error("  "+file.getName()+"      !");
            throw new BusinessException("  "+file.getName()+"      !");
        }

        //  sheet   
        int columns = sheet.getRow(SHEET_START_ROW_NUMBER).getLastCellNum();
        //       class  --  --   
        columnClassNamez = new Field[columns-SHEET_START_COLUMN_NUMBER];
        //    --  --   
        columnNamez = new String[columns-SHEET_START_COLUMN_NUMBER];

        //  Field[]  className classPath
        Class> clazz = getThisClass(entity);
        Field[]  fieldz = clazz.getDeclaredFields();
        //          ,         javabean  
        for(int i=SHEET_START_COLUMN_NUMBER;i//      
            columnNamez[i-SHEET_START_COLUMN_NUMBER] = sheet.getRow(SHEET_START_ROW_NUMBER).getCell(i).getStringCellValue();
            //         class  
            columnClassNamez[i-SHEET_START_COLUMN_NUMBER] = queryClassName(columnNamez[i-SHEET_START_COLUMN_NUMBER],fieldz);
        }


        //   
        for(int i=SHEET_START_ROW_NUMBER+1;i1;i++){
            //        
            if(readover){
                break;
            }

            Object obj = null;
            try {
                obj = clazz.newInstance();
            } catch (InstantiationException e) {
                log.error("        !");
                throw new BusinessException(e.getMessage());
            } catch (IllegalAccessException e) {
                log.error("        !");
                throw new BusinessException(e.getMessage());
            }

            try{
                //         ,        
                if(null == sheet.getRow(i).getCell(SHEET_START_COLUMN_NUMBER)){
                    log.error(" "+(i+1)+"    !");
                    throw new BusinessException(" "+(i+1)+"    !");
                }

                //     
                for(int j=SHEET_START_COLUMN_NUMBER;jnull;

                    //           ,     set   
                    if(null == sheet.getRow(i).getCell(j)){
                        continue;
                    }

                    try {
                        method = obj.getClass().getMethod("set"+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(0,1).toUpperCase()+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(1),columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getType() );
                    } catch (SecurityException e) {
                        log.error("  set     :"+"set"+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(0,1).toUpperCase()+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(1));
                        throw new BusinessException("  set     :"+"set"+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(0,1).toUpperCase()+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(1));
                    } catch (NoSuchMethodException e) {
                        log.error("  set     :"+"set"+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(0,1).toUpperCase()+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(1));
                        throw new BusinessException("  set     :"+"set"+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(0,1).toUpperCase()+columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getName().substring(1));
                    }

                    try {
                        method.invoke(obj, getmethodInvokeValue(sheet.getRow(i).getCell(j),columnClassNamez[j-SHEET_START_COLUMN_NUMBER].getType().getName()));
                    } catch (IllegalArgumentException e) {
                        log.error(" :"+i+" :"+j+",   "+sheet.getRow(i).getCell(j).getStringCellValue()+"     ");
                        throw new BusinessException(" :"+(i+1)+" :"+(j+1)+",   "+sheet.getRow(i).getCell(j).getStringCellValue()+"     ");
                    } catch (IllegalAccessException e) {
                        log.error(" :"+i+" :"+j+",   "+sheet.getRow(i).getCell(j).getStringCellValue()+"     ");
                        throw new BusinessException(" :"+(i+1)+" :"+(j+1)+",   "+sheet.getRow(i).getCell(j).getStringCellValue()+"     ");
                    } catch (InvocationTargetException e) {
                        log.error(" :"+i+" :"+j+",   "+sheet.getRow(i).getCell(j).getStringCellValue()+"     ");
                        throw new BusinessException(" :"+(i+1)+" :"+(j+1)+",   "+sheet.getRow(i).getCell(j).getStringCellValue()+"     ");
                    }
                }
                //        Obj   list   
                list.add(obj);
            }catch(Exception e){
                //       -      
                log.error("    , :"+(i+1)+",    :"+e.getMessage()+"     list -start");
                //           
                String[] errorz = new String[columns-SHEET_START_COLUMN_NUMBER];
                //     
                for(int x=SHEET_START_COLUMN_NUMBER;x"    , :"+(i+1)+",    :"+e.getMessage());
                log.error("    , :"+(i+1)+",    :"+e.getMessage()+"     list -end");
            }
        }
        responseentity.setFile(file);
        responseentity.setColumnNamez(columnNamez);
        responseentity.setColumnClassNamez(columnClassNamez);
        responseentity.setList(list);
        responseentity.setErrorlist(errorlist);
        responseentity.setErrorMessagelist(errorMessagelist);
        responseentity.setClassName(entity.getClassName());
//      responseentity.setClassPath(entity.getClassPath());
        return responseentity;
    }


    /**
     *   Field[]  className classPath
     * @param entity
     * @return
     */
    public Class> getThisClass(AnalysisFileEntity entity){
        Class> clazz = null;
        try {
            clazz = Class.forName(entity.getClassName());
        } catch (ClassNotFoundException e) {
            log.error(entity.getClassName()+",     ");
            throw new BusinessException(e.getMessage());
        }
        return clazz;
    }

    /**
     *     ,  javabean  name
     * @param CellName
     * @param entity
     * @return
     */
    public Field queryClassName(String cellName,Field[]  fieldz){
        Field field= null;
         for(int i=0;iif(null != annotation){
                 XmlElement xmlelement = (XmlElement) annotation;
                 //           
                 if(!xmlelement.name().equals("##default")) {
                     //              
                     if(cellName.equals(xmlelement.name())){
                         break;
                     }else{
                         field= null;
                     }
                 }
             }else{
                 field= null;
             }
         }
         if(null == field){
             log.error(" :"+cellName+"          ");
             throw new BusinessException(" :"+cellName+"          ");
         }
        return field;
    }

    public Object getCellContent(String cellContent,String classType){

        /** 
           *     、    、String   
           */  
        try{
            if(classType.equals("java.math.BigDecimal")){
                return new BigDecimal(cellContent);
            }else if(classType.equals("java.util.Date")){
                SimpleDateFormat sm = new SimpleDateFormat("YYYY-MM-DD HH24:mm:ss");
                try {
                    return sm.parse(cellContent);
                } catch (ParseException e) {
                    log.error("     :"+cellContent+",  ");
                    throw new BusinessException("     :"+cellContent+",  ");
                }
            }else if(classType.equals("java.lang.Integer") || classType.equals("int")){
                return Integer.parseInt(cellContent);
            }else if(classType.equals("java.lang.Double")|| classType.equals("double")){
                return Double.parseDouble(cellContent);
            }else if(classType.equals("java.lang.Float")|| classType.equals("float")){
                return Float.parseFloat(cellContent);
            }else if(classType.equals("java.lang.Long") || classType.equals("long")){
                return Long.parseLong(cellContent);
            }else if(classType.equals("java.lang.Short") || classType.equals("short")){
                return Short.parseShort(cellContent);
            }else if(classType.equals("java.lang.Byte") || classType.equals("byte")){
                return Byte.parseByte(cellContent);
            }else if(classType.equals("java.lang.Boolean") || classType.equals("boolean")){
                return Boolean.parseBoolean(cellContent);
            }else if(classType.equals("java.lang.Character") || classType.equals("char")){
                return cellContent.toCharArray()[0];
            }else{
                return cellContent;
            }
        }catch(Exception e){
            log.error("    "+cellContent+"   ,  ");
            throw new BusinessException("    "+cellContent+"   ,  ");
        }
    }

    /**
     *     
     * @param str
     * @return
     */
    public static String replaceBlank(String str){
        if(StringUtils.isEmpty(str)){
            return "";
        }
        Pattern pattern = Pattern.compile("\\s*|\t|\r|
"
); Matcher m = pattern.matcher(str); return m.replaceAll(""); } /** * * @param xssfRow * @return */ private Object getmethodInvokeValue(XSSFCell xssfRow, String classType) { Object cellvalue = null; if (xssfRow.getCellType() == Cell.CELL_TYPE_BOOLEAN) { cellvalue = xssfRow.getBooleanCellValue(); } else if (xssfRow.getCellType() == Cell.CELL_TYPE_NUMERIC) { cellvalue = xssfRow.getNumericCellValue(); } else { cellvalue = xssfRow.getStringCellValue(); } String cellContent = String.valueOf(cellvalue); /** * 、 、String */ try{ if(classType.equals("java.math.BigDecimal")){ return new BigDecimal(cellContent); }else if(classType.equals("java.util.Date")){ try { if(xssfRow.getCellType() == Cell.CELL_TYPE_NUMERIC ){ if (HSSFDateUtil.isCellDateFormatted(xssfRow)){ SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String datestr =dateFormat.format(xssfRow.getDateCellValue()); return dateFormat.parse(datestr); }else{ return xssfRow.getNumericCellValue(); } }else{ SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); return dateFormat.parse(xssfRow.getStringCellValue()); } } catch (BusinessException e) { log.error(" :"+cellvalue+", "); throw new BusinessException(" :"+cellvalue+", "); } }else if(classType.equals("java.lang.Integer") || classType.equals("int")){ cellContent = removepoint(cellContent); return Integer.valueOf(cellContent); }else if(classType.equals("java.lang.Double")|| classType.equals("double")){ return Double.parseDouble(cellContent); }else if(classType.equals("java.lang.Float")|| classType.equals("float")){ return Float.parseFloat(cellContent); }else if(classType.equals("java.lang.Long") || classType.equals("long")){ return Long.parseLong(cellContent); }else if(classType.equals("java.lang.Short") || classType.equals("short")){ cellContent = removepoint(cellContent); return Short.parseShort(cellContent); }else if(classType.equals("java.lang.Byte") || classType.equals("byte")){ cellContent = removepoint(cellContent); return Byte.parseByte(cellContent); }else if(classType.equals("java.lang.Boolean") || classType.equals("boolean")){ return Boolean.parseBoolean(cellContent); }else if(classType.equals("java.lang.Character") || classType.equals("char")){ cellContent = removepoint(cellContent); return cellContent.toCharArray()[0]; }else{ cellContent = removepoint(cellContent); return cellContent; } }catch(Exception e){ log.error(" "+cellvalue+" , "); throw new BusinessException(" "+cellvalue+" , "); } } /** * , String * @param xssfRow * @return */ private String getStrValue(XSSFCell xssfRow) { if(null == xssfRow){ return null; } if (xssfRow.getCellType() == Cell.CELL_TYPE_BOOLEAN) { return String.valueOf(xssfRow.getBooleanCellValue()); } else if (xssfRow.getCellType() == Cell.CELL_TYPE_NUMERIC) { return String.valueOf(xssfRow.getNumericCellValue()); } else { return String.valueOf(xssfRow.getStringCellValue()); } } /** * * @param cellContent * @return */ private String removepoint(String cellContent){ int index = cellContent.indexOf("."); if(index == -1){ return cellContent; } return cellContent.substring(0, index); } /** * excel, , * @param title * @param headerlist * @param filedNamelist * @param exporttoexcelentitylist * @param out * @param pattern * @param pattern1 */ public ByteArrayOutputStream exportExcel(String title,AnalysisResponseEntity entity){ String[] headerz = entity.getColumnNamez(); List exporttoexcelentitylist = entity.getErrorlist(); Field[] filedNamez = entity.getColumnClassNamez(); List errorMessageList = entity.getErrorMessagelist(); ByteArrayOutputStream out = new ByteArrayOutputStream(); /** * */ XSSFWorkbook workbook = new XSSFWorkbook(); /** * */ XSSFSheet sheet = workbook.createSheet(title); /** * */ sheet.setDefaultColumnWidth(headerz.length); /** * */ XSSFCellStyle style = workbook.createCellStyle(); /** * */ style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); /** * */ XSSFFont font = workbook.createFont(); font.setColor(HSSFColor.VIOLET.index); font.setFontHeightInPoints((short) 12); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); /** * */ style.setFont(font); /** * */ XSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); /** * */ XSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); /** * */ style2.setFont(font2); /** * */ XSSFRow titlerow = sheet.createRow(SHEET_START_ROW_NUMBER); for (int i = 0; i < headerz.length; i++){ XSSFCell cell = titlerow.createCell(i); cell.setCellStyle(style); XSSFRichTextString text = new XSSFRichTextString(headerz[i]); cell.setCellValue(text); } /** * , */ if(exporttoexcelentitylist != null && exporttoexcelentitylist.size()>0){ for(int i=0;i1); for(int j=0;jtry { XSSFCell cell = row.createCell(SHEET_START_COLUMN_NUMBER+j); cell.setCellStyle(style2); if(null != entity1[j]){ cell.setCellValue(entity1[j]); } } catch (SecurityException e) { log.error(" Cell :"+e.getMessage()); throw new BusinessException(" Cell :"+e.getMessage()); } } } } // sheet2 /** * sheet */ XSSFSheet sheet2 = workbook.createSheet(" "); // for(int i=0;itry { workbook.write(out); } catch (IOException e1) { log.error(" workbook :"+e1.getMessage()); throw new BusinessException(" workbook :"+e1.getMessage()); } return out; } /** * , excel , excel * @param sourcefile * @param entity * @return */ public String createExcel(File sourcefile,AnalysisResponseEntity entity){ File oldfile = entity.getFile(); String filepath = oldfile.getAbsolutePath().substring(0,(int)oldfile.getAbsoluteFile().toString().length()-oldfile.getName().length()); String filename = oldfile.getName().substring(0, oldfile.getName().replaceAll("_UN", "").indexOf("."))+"_ErrorList"+oldfile.getName().substring(oldfile.getName().indexOf(".")); File destFile = new File(filepath+filename); // try { FileUtils.copyFile(sourcefile, destFile); } catch (IOException e) { log.error(" ! "+e.getMessage()); throw new BusinessException(" ! "+e.getMessage()); } // List exporttoexcelentitylist = entity.getErrorlist(); // javabean Field Field[] filedNamez = entity.getColumnClassNamez(); // // // ByteArrayOutputStream out = new ByteArrayOutputStream(); FileOutputStream out = null; // List errorMessageList = entity.getErrorMessagelist(); // String[] columnNamez = entity.getColumnNamez(); /** * */ XSSFWorkbook workbook = null; try { workbook = new XSSFWorkbook(new FileInputStream(destFile)); } catch (FileNotFoundException e2) { log.error(" :"+destFile.getName()+", Excel !, :"+e2.getMessage()); throw new BusinessException(" :"+destFile.getName()+", Excel !, :"+e2.getMessage()); } catch (IOException e2) { log.error(" :"+destFile.getName()+", Excel !, :"+e2.getMessage()); throw new BusinessException(" :"+destFile.getName()+", Excel !, :"+e2.getMessage()); } /** * sheet */ XSSFSheet sheet = workbook.getSheetAt(0); // XSSFRow titlerow = sheet.getRow(SHEET_START_ROW_NUMBER); for(int i=0;iif(!columnNamez[i].equals(titlerow.getCell(i+SHEET_START_COLUMN_NUMBER).getStringCellValue())){ log.error(" , "); throw new BusinessException(" , "); } } /** * , */ if(exporttoexcelentitylist != null && exporttoexcelentitylist.size()>0){ for(int i=0;i1); for(int j=0;jtry { XSSFCell cell = row.createCell(SHEET_START_COLUMN_NUMBER+j); if(null != entity1[j]){ cell.setCellValue(entity1[j]); } } catch (SecurityException e) { log.error(" Cell :"+e.getMessage()); throw new BusinessException(" Cell :"+e.getMessage()); } } } // sheet2 /** * sheet */ XSSFSheet sheet2 = workbook.getSheetAt(1); // for(int i=0;i// , }else{ return null; } try { out = new FileOutputStream(destFile); workbook.write(out); } catch (IOException e1) { log.error(" workbook :"+e1.getMessage()); throw new BusinessException(" workbook :"+e1.getMessage()); } return destFile.getPath(); } /** * excel, , excel * @param title * @param headerlist * @param filedNamelist * @param exporttoexcelentitylist * @param out * @param pattern * @param pattern1 */ public ByteArrayOutputStream exportExcel(File file,AnalysisResponseEntity entity){ // List exporttoexcelentitylist = entity.getErrorlist(); // javabean Field Field[] filedNamez = entity.getColumnClassNamez(); // ByteArrayOutputStream out = new ByteArrayOutputStream(); // List errorMessageList = entity.getErrorMessagelist(); // String[] columnNamez = entity.getColumnNamez(); /** * */ XSSFWorkbook workbook = null; try { workbook = new XSSFWorkbook(new FileInputStream(file)); } catch (FileNotFoundException e2) { log.error(" :"+file.getName()+", Excel !, :"+e2.getMessage()); throw new BusinessException(" :"+file.getName()+", Excel !, :"+e2.getMessage()); } catch (IOException e2) { log.error(" :"+file.getName()+", Excel !, :"+e2.getMessage()); throw new BusinessException(" :"+file.getName()+", Excel !, :"+e2.getMessage()); } /** * sheet */ XSSFSheet sheet = workbook.getSheetAt(0); // XSSFRow titlerow = sheet.getRow(SHEET_START_ROW_NUMBER); for(int i=0;iif(!columnNamez[i].equals(titlerow.getCell(i+SHEET_START_COLUMN_NUMBER).getStringCellValue())){ log.error(" , "); throw new BusinessException(" , "); } } /** * , */ if(exporttoexcelentitylist != null && exporttoexcelentitylist.size()>0){ for(int i=0;i1); for(int j=0;jtry { XSSFCell cell = row.createCell(SHEET_START_COLUMN_NUMBER+j); if(null != entity1[j]){ cell.setCellValue(entity1[j]); } } catch (SecurityException e) { log.error(" Cell :"+e.getMessage()); throw new BusinessException(" Cell :"+e.getMessage()); } } } // sheet2 /** * sheet */ XSSFSheet sheet2 = workbook.createSheet(" "); // for(int i=0;itry { workbook.write(out); } catch (IOException e1) { log.error(" workbook :"+e1.getMessage()); throw new BusinessException(" workbook :"+e1.getMessage()); } return out; } /** * excel * @param os * @param response */ public void download(String path, HttpServletResponse response) { if(StringUtils.isEmpty(path)){ log.error("path !"); throw new BusinessException("path !"); } File file = new File(path); if(!file.exists()){ log.error(" :"+path+", !"); throw new BusinessException(" :"+path+", !"); } try { OutputStream os = new FileOutputStream(file); byte[] content = ((ByteArrayOutputStream) os).toByteArray(); InputStream is = new ByteArrayInputStream(content); response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(("transactionManagementlist".toString() + ".xls").getBytes(), "iso-8859-1")); response.setCharacterEncoding("utf-8"); ServletOutputStream out = response.getOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[1024]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (final IOException e) { throw e; } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); os.close(); } }catch(Exception e){ e.printStackTrace(); } } }

두 개의 Javabean 중 하 나 는 Analysis FileEntity 입 니 다. 이 정 의 는 엑셀 파일 의 내 제목 이 전 달 된 클래스 와 대응 하 는 클래스 입 니 다.
package com.deppon.tps.module.aboutexcel.server.shared.domain;

import java.io.File;

public class AnalysisFileEntity {

    //     
    public File file;
    //   class,   name
    public String className;
//  //   class,   path
//  public String classPath;
    /**
     * @return the file
     */
    public File getFile() {
        return file;
    }
    /**
     * @param file the file to set
     */
    public void setFile(File file) {
        this.file = file;
    }
    /**
     * @return the className
     */
    public String getClassName() {
        return className;
    }
    /**
     * @param className the className to set
     */
    public void setClassName(String className) {
        this.className = className;
    }
//  /**
//   * @return the classPath
//   */
//  public String getClassPath() {
//      return classPath;
//  }
//  /**
//   * @param classPath the classPath to set
//   */
//  public void setClassPath(String classPath) {
//      this.classPath = classPath;
//  }




}

이 JavaBean - AnalysisResponseEntity 는 해 석 된 데 이 터 를 저장 하 는 데 사 용 됩 니 다.
package com.deppon.tps.module.aboutexcel.server.shared.domain;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

public class AnalysisResponseEntity extends AnalysisFileEntity{

    //       class  --  
    Field[] columnClassNamez = null;
    //    --  
    String[] columnNamez = null; 
    // excel          
    List list = new LinkedList();
    // excel          
    List errorlist = new LinkedList();
    // excel          
    List errorMessagelist = new LinkedList();
    /**
     * @return the columnClassNamez
     */
    public Field[] getColumnClassNamez() {
        return columnClassNamez;
    }
    /**
     * @param columnClassNamez the columnClassNamez to set
     */
    public void setColumnClassNamez(Field[] columnClassNamez) {
        this.columnClassNamez = columnClassNamez;
    }
    /**
     * @return the columnNamez
     */
    public String[] getColumnNamez() {
        return columnNamez;
    }
    /**
     * @param columnNamez the columnNamez to set
     */
    public void setColumnNamez(String[] columnNamez) {
        this.columnNamez = columnNamez;
    }
    /**
     * @return the list
     */
    public List getList() {
        return list;
    }
    /**
     * @param list the list to set
     */
    public void setList(List list) {
        this.list = list;
    }
    /**
     * @return the errorlist
     */
    public List getErrorlist() {
        return errorlist;
    }
    /**
     * @param errorlist the errorlist to set
     */
    public void setErrorlist(List errorlist) {
        this.errorlist = errorlist;
    }
    /**
     * @return the errorMessagelist
     */
    public List getErrorMessagelist() {
        return errorMessagelist;
    }
    /**
     * @param errorMessagelist the errorMessagelist to set
     */
    public void setErrorMessagelist(List errorMessagelist) {
        this.errorMessagelist = errorMessagelist;
    }
}

* 테스트 클래스 입 니 다 *
    @Test
    public void importFileData(){

        AnalysisFileEntity entity = new AnalysisFileEntity();
        File sourcefile = new File("d:\\314746\\Desktop\\test\\testexcel-UN.xlsx");
        File file = new File("d:\\314746\\Desktop\\test\\testexcel1.xlsx");
        entity.setFile(file);
        String className = "com.deppon.tps.module.aboutexcel.server.poidwexcel.shared.domain.testEntity";
        entity.setClassName(className);
        AnalysisResponseEntity  entity1 = poidwExcelUtlsServiceImpl.importFileData(entity);
        List list = entity1.getList();
        for(int i=0;iget(i);
            testEntity entity2 = (testEntity)obj;
            System.out.println(entity2.getIndex());
        }
        //        
        if(null !=entity1.getErrorlist() && entity1.getErrorlist().size()>0){
            String path = poidwExcelUtlsServiceImpl.createExcel(sourcefile,entity1);
            System.out.println(path);
        }
    }

좋은 웹페이지 즐겨찾기