ExportUtil导出、导入工具类

1、ExportUtil导出工具类(根据模板导出),支持2003/2007不同excel格式文件

  1. package org.nercita.bcp.util;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.net.URLEncoder;  
  7. import java.util.Iterator;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10. import java.util.Properties;  
  11.   
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. import net.sf.jxls.transformer.XLSTransformer;  
  16.   
  17. import org.apache.commons.io.IOUtils;  
  18. import org.apache.commons.lang.StringUtils;  
  19. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  20. import org.apache.poi.hssf.usermodel.HSSFFont;  
  21. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  22. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
  23. import org.apache.poi.ss.usermodel.Cell;  
  24. import org.apache.poi.ss.usermodel.Row;  
  25. import org.apache.poi.ss.usermodel.Sheet;  
  26. import org.apache.poi.ss.usermodel.Workbook;  
  27. import org.apache.poi.ss.util.CellRangeAddress;  
  28. import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
  29. import org.apache.poi.xssf.usermodel.XSSFFont;  
  30. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  31. import org.springframework.core.io.ClassPathResource;  
  32. import org.springframework.util.Assert;  
  33.   
  34. /**  
  35.  * 导出工具类  
  36.  */  
  37. public class ExportUtil {  
  38.     public static String EXCEL_2007 = “Excel2007”;  
  39.     public static String EXCEL_2003 = “Excel2003”;  
  40.     private volatile Properties props = new Properties();  
  41.     private boolean inited = false;  
  42.     private volatile static ExportUtil util = new ExportUtil();  
  43.   
  44.     private ExportUtil() {  
  45.         init();  
  46.     }  
  47.   
  48.     public Properties getProps() {  
  49.         if (!inited)  
  50.             init();  
  51.         return props;  
  52.     }  
  53.   
  54.     public String getProp(String key) {  
  55.         if (!inited)  
  56.             init();  
  57.         return props.getProperty(key);  
  58.     }  
  59.   
  60.     public String getProp(String key, String defaultValue) {  
  61.         if (!inited)  
  62.             init();  
  63.         return props.getProperty(key, defaultValue);  
  64.     }  
  65.   
  66.   
  67.     private void init() {  
  68.         try {  
  69.             InputStream is = new ClassPathResource(“export.properties”).getInputStream();  
  70.             props.load(is);  
  71.             is.close();  
  72.             inited = true;  
  73.         } catch (IOException e) {  
  74.             e.printStackTrace();  
  75.         }  
  76.     }  
  77.   
  78.     public static ExportUtil getUtil() {  
  79.         if (util == null)  
  80.             util = new ExportUtil();  
  81.         return util;  
  82.     }  
  83.   
  84.     /**  
  85.      * 设置下载文件中文件的名称  
  86.      *  
  87.      * @param pFileName  
  88.      * @param request  
  89.      * @return  
  90.      */  
  91.     public static String encodeFilename(String pFileName, HttpServletRequest request){  
  92.         String filename = null;      
  93.         String agent = request.getHeader(“USER-AGENT”);  
  94.         try {  
  95.                   
  96.             if (null != agent){      
  97.                 if (-1 != agent.indexOf(“Firefox”)) {//Firefox      
  98.                     filename = “=?UTF-8?B?” + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes(“UTF-8”))))+ ”?=”;      
  99.                 }else if (-1 != agent.indexOf(“Chrome”)) {//Chrome      
  100.                     filename = new String(pFileName.getBytes(), “ISO8859-1”);      
  101.                 } else {//IE7+      
  102.                     filename = URLEncoder.encode(pFileName, “UTF-8”);      
  103.                     filename = StringUtils.replace(filename, ”+”, ”%20”);//替换空格      
  104.                 }      
  105.             } else {      
  106.                 filename = pFileName;      
  107.             }      
  108.              
  109.         } catch (Exception ex) {  
  110.   
  111.         }  
  112.          return filename;  
  113.    }  
  114.   
  115.     //导出  
  116.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response,   
  117.             String version, String templatePath, Map<String, Object> beanParams,Map<Integer,List<CellFill>> mapFill) {  
  118.         writeResponse(fileName, request, response, version, templatePath, beanParams, false, null, null, mapFill);  
  119.     }  
  120.       
  121.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response,   
  122.             String version, String templatePath, Map<String, Object> beanParams) {  
  123.         writeResponse(fileName, request, response, version, templatePath, beanParams, false, null, null, null);  
  124.     }  
  125.   
  126.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,  
  127.                                      boolean innerCollectionAccess) {  
  128.         writeResponse(fileName, request, response, version, templatePath, beanParams, innerCollectionAccess, null, null, null);  
  129.     }  
  130.   
  131.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,  
  132.                                      boolean innerCollectionAccess, Map<Integer, List<CellRangeAddress>> rangeMap) {  
  133.         writeResponse(fileName, request, response, version, templatePath, beanParams, innerCollectionAccess, rangeMap, null, null);  
  134.     }  
  135.   
  136.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,  
  137.                                      Map<Integer, List<CellRangeAddress>> rangeMap, XLSTransformer transformer) {  
  138.         writeResponse(fileName, request, response, version, templatePath, beanParams, false, rangeMap, transformer, null);  
  139.     }  
  140.   
  141.     //  
  142.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response,   
  143.             String version, String templatePath, Map<String, Object> beanParams,  
  144.             boolean innerCollectionAccess, Map<Integer, List<CellRangeAddress>> rangeMap, XLSTransformer trans,  
  145.             Map<Integer,List<CellFill>> mapFill) {  
  146.         Assert.isTrue(StringUtils.isNotBlank(templatePath), “templatePath不可以为空字符串”);  
  147.         XLSTransformer transformer = null;  
  148.         if (trans != null) {  
  149.             transformer = trans;  
  150.         } else {  
  151.             transformer = new XLSTransformer();  
  152.         }  
  153.         transformer.setJexlInnerCollectionsAccess(innerCollectionAccess);  
  154.         response.setCharacterEncoding(“utf-8”);  
  155.         if (EXCEL_2007.equals(version)) {  
  156.             fileName = encodeFilename(fileName + ”.xlsx”, request);  
  157.             response.setContentType(“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8”);  
  158.         } else {  
  159.             fileName = encodeFilename(fileName + ”.xls”, request);  
  160.             response.setContentType(“application/vnd.ms-excel;charset=UTF-8”);  
  161.         }  
  162.         response.setHeader(“Content-Disposition”, “attachment;fileName=” + fileName);  
  163.         InputStream is = null;  
  164.         try {  
  165.             if(“linux”.equals(System.getProperty(“os.name”).toLowerCase())){  
  166.                 if(!templatePath.startsWith(“/”)){  
  167.                     templatePath=“/”+templatePath;  
  168.                 }  
  169.             }  
  170.             is = new FileInputStream(templatePath);  
  171.             Workbook book = transformer.transformXLS(is, beanParams);  
  172.             if (rangeMap != null) {  
  173.                 Iterator<Integer> index = rangeMap.keySet().iterator();  
  174.                 while (index.hasNext()) {  
  175.                     Integer i = index.next();  
  176.                     Sheet sheet = book.getSheetAt(i);  
  177.                     Iterator<CellRangeAddress> cra = rangeMap.get(i).iterator();  
  178.                     while (cra.hasNext()) {  
  179.                         sheet.addMergedRegion(cra.next());  
  180.                     }  
  181.                 }  
  182.             }  
  183.               
  184.             //==========填充颜色,add by psh   
  185.            if(mapFill!=null) {  
  186.                if (EXCEL_2003.equals(version)) {  
  187.                    HSSFWorkbook workbook=(HSSFWorkbook)book;  
  188.                    Iterator<Integer> sheetIndex = mapFill.keySet().iterator();  
  189.                    while (sheetIndex.hasNext()) {  
  190.                        Integer index = sheetIndex.next();  
  191.                        Sheet sheet = workbook.getSheetAt(index);  
  192.                        List<CellFill> list = mapFill.get(index);  
  193.                        CellFill cellFillnull;  
  194.                        for(int i=0;i<list.size();i++){  
  195.                            cellFilllist.get(i);  
  196.                            Row row = (Row)sheet.getRow(cellFill.getRow());  
  197.                            if(row==null){  
  198.                                continue;  
  199.                            }  
  200.                            Cell cell = row.getCell(cellFill.getCol());  
  201.                            if(cell==null){  
  202.                                continue;  
  203.                            }  
  204.                            HSSFCellStyle sheetStyle = workbook.createCellStyle();     //Sheet样式  
  205.                            sheetStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //填充模式  
  206.                            sheetStyle.setFillForegroundColor(cellFill.getBgColor()); //前景色(单元格)的设定。HSSFColor.YELLOW.index——黄色  
  207.                            HSSFFont font=workbook.createFont();  
  208.                            font.setColor(cellFill.getFontColor());  
  209.                            sheetStyle.setFont(font);                   
  210.                            cell.setCellStyle(sheetStyle);  
  211.                        }  
  212.                    }//end while  
  213.                }else {  
  214.                    XSSFWorkbook workbook=(XSSFWorkbook)book;  
  215.                    Iterator<Integer> sheetIndex = mapFill.keySet().iterator();  
  216.                    while (sheetIndex.hasNext()) {  
  217.                        Integer index = sheetIndex.next();  
  218.                        Sheet sheet = workbook.getSheetAt(index);  
  219.                        List<CellFill> list = mapFill.get(index);  
  220.                        CellFill cellFillnull;  
  221.                        for(int i=0;i<list.size();i++){  
  222.                            cellFilllist.get(i);  
  223.                            Row row = (Row)sheet.getRow(cellFill.getRow());  
  224.                            if(row==null){  
  225.                                continue;  
  226.                            }  
  227.                            Cell cell = row.getCell(cellFill.getCol());  
  228.                            if(cell==null){  
  229.                                continue;  
  230.                            }  
  231.                            XSSFCellStyle sheetStyle = workbook.createCellStyle();     //Sheet样式  
  232.                            sheetStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //填充模式  
  233.                            sheetStyle.setFillForegroundColor(cellFill.getBgColor()); //前景色(单元格)的设定。HSSFColor.YELLOW.index——黄色  
  234.                            XSSFFont font=workbook.createFont();  
  235.                            font.setColor(cellFill.getFontColor());  
  236.                            sheetStyle.setFont(font);                   
  237.                            cell.setCellStyle(sheetStyle);  
  238.                        }  
  239.                    }//end while  
  240.                } //end 2007          
  241.            }             
  242.            //=====end 颜色===========  
  243.               
  244.            book.write(response.getOutputStream());                    
  245.         } catch (IOException e) {  
  246.             e.printStackTrace();  
  247.         } catch (InvalidFormatException e) {  
  248.             e.printStackTrace();  
  249.         } finally {  
  250.             IOUtils.closeQuietly(is);  
  251.         }  
  252.     }  
  253.   
  254.     public static String getProperty(String property) {  
  255.         return getUtil().getProp(property);  
  256.     }  
  257. }  
package org.nercita.bcp.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;

/**
 * 导出工具类
 */
public class ExportUtil {
    public static String EXCEL_2007 = "Excel2007";
    public static String EXCEL_2003 = "Excel2003";
    private volatile Properties props = new Properties();
    private boolean inited = false;
    private volatile static ExportUtil util = new ExportUtil();

    private ExportUtil() {
        init();
    }

    public Properties getProps() {
        if (!inited)
            init();
        return props;
    }

    public String getProp(String key) {
        if (!inited)
            init();
        return props.getProperty(key);
    }

    public String getProp(String key, String defaultValue) {
        if (!inited)
            init();
        return props.getProperty(key, defaultValue);
    }


    private void init() {
        try {
            InputStream is = new ClassPathResource("export.properties").getInputStream();
            props.load(is);
            is.close();
            inited = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ExportUtil getUtil() {
        if (util == null)
            util = new ExportUtil();
        return util;
    }

    /**
     * 设置下载文件中文件的名称
     *
     * @param pFileName
     * @param request
     * @return
     */
    public static String encodeFilename(String pFileName, HttpServletRequest request){
        String filename = null;    
        String agent = request.getHeader("USER-AGENT");
        try {

            if (null != agent){    
                if (-1 != agent.indexOf("Firefox")) {//Firefox    
                    filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8"))))+ "?=";    
                }else if (-1 != agent.indexOf("Chrome")) {//Chrome    
                    filename = new String(pFileName.getBytes(), "ISO8859-1");    
                } else {//IE7+    
                    filename = URLEncoder.encode(pFileName, "UTF-8");    
                    filename = StringUtils.replace(filename, "+", "%20");//替换空格    
                }    
            } else {    
                filename = pFileName;    
            }    

        } catch (Exception ex) {

        }
         return filename;
   }

    //导出
    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, 
            String version, String templatePath, Map<String, Object> beanParams,Map<Integer,List<CellFill>> mapFill) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, false, null, null, mapFill);
    }

    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, 
            String version, String templatePath, Map<String, Object> beanParams) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, false, null, null, null);
    }

    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,
                                     boolean innerCollectionAccess) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, innerCollectionAccess, null, null, null);
    }

    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,
                                     boolean innerCollectionAccess, Map<Integer, List<CellRangeAddress>> rangeMap) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, innerCollectionAccess, rangeMap, null, null);
    }

    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,
                                     Map<Integer, List<CellRangeAddress>> rangeMap, XLSTransformer transformer) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, false, rangeMap, transformer, null);
    }

    //
    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, 
            String version, String templatePath, Map<String, Object> beanParams,
            boolean innerCollectionAccess, Map<Integer, List<CellRangeAddress>> rangeMap, XLSTransformer trans,
            Map<Integer,List<CellFill>> mapFill) {
        Assert.isTrue(StringUtils.isNotBlank(templatePath), "templatePath不可以为空字符串");
        XLSTransformer transformer = null;
        if (trans != null) {
            transformer = trans;
        } else {
            transformer = new XLSTransformer();
        }
        transformer.setJexlInnerCollectionsAccess(innerCollectionAccess);
        response.setCharacterEncoding("utf-8");
        if (EXCEL_2007.equals(version)) {
            fileName = encodeFilename(fileName + ".xlsx", request);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        } else {
            fileName = encodeFilename(fileName + ".xls", request);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        InputStream is = null;
        try {
            if("linux".equals(System.getProperty("os.name").toLowerCase())){
                if(!templatePath.startsWith("/")){
                    templatePath="/"+templatePath;
                }
            }
            is = new FileInputStream(templatePath);
            Workbook book = transformer.transformXLS(is, beanParams);
            if (rangeMap != null) {
                Iterator<Integer> index = rangeMap.keySet().iterator();
                while (index.hasNext()) {
                    Integer i = index.next();
                    Sheet sheet = book.getSheetAt(i);
                    Iterator<CellRangeAddress> cra = rangeMap.get(i).iterator();
                    while (cra.hasNext()) {
                        sheet.addMergedRegion(cra.next());
                    }
                }
            }

            //==========填充颜色,add by psh 
           if(mapFill!=null) {
               if (EXCEL_2003.equals(version)) {
                   HSSFWorkbook workbook=(HSSFWorkbook)book;
                   Iterator<Integer> sheetIndex = mapFill.keySet().iterator();
                   while (sheetIndex.hasNext()) {
                       Integer index = sheetIndex.next();
                       Sheet sheet = workbook.getSheetAt(index);
                       List<CellFill> list = mapFill.get(index);
                       CellFill cellFill= null;
                       for(int i=0;i<list.size();i++){
                           cellFill= list.get(i);
                           Row row = (Row)sheet.getRow(cellFill.getRow());
                           if(row==null){
                               continue;
                           }
                           Cell cell = row.getCell(cellFill.getCol());
                           if(cell==null){
                               continue;
                           }
                           HSSFCellStyle sheetStyle = workbook.createCellStyle();     //Sheet样式
                           sheetStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //填充模式
                           sheetStyle.setFillForegroundColor(cellFill.getBgColor()); //前景色(单元格)的设定。HSSFColor.YELLOW.index——黄色
                           HSSFFont font=workbook.createFont();
                           font.setColor(cellFill.getFontColor());
                           sheetStyle.setFont(font);                 
                           cell.setCellStyle(sheetStyle);
                       }
                   }//end while
               }else {
                   XSSFWorkbook workbook=(XSSFWorkbook)book;
                   Iterator<Integer> sheetIndex = mapFill.keySet().iterator();
                   while (sheetIndex.hasNext()) {
                       Integer index = sheetIndex.next();
                       Sheet sheet = workbook.getSheetAt(index);
                       List<CellFill> list = mapFill.get(index);
                       CellFill cellFill= null;
                       for(int i=0;i<list.size();i++){
                           cellFill= list.get(i);
                           Row row = (Row)sheet.getRow(cellFill.getRow());
                           if(row==null){
                               continue;
                           }
                           Cell cell = row.getCell(cellFill.getCol());
                           if(cell==null){
                               continue;
                           }
                           XSSFCellStyle sheetStyle = workbook.createCellStyle();     //Sheet样式
                           sheetStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //填充模式
                           sheetStyle.setFillForegroundColor(cellFill.getBgColor()); //前景色(单元格)的设定。HSSFColor.YELLOW.index——黄色
                           XSSFFont font=workbook.createFont();
                           font.setColor(cellFill.getFontColor());
                           sheetStyle.setFont(font);                 
                           cell.setCellStyle(sheetStyle);
                       }
                   }//end while
               } //end 2007        
           }           
           //=====end 颜色===========

           book.write(response.getOutputStream());                  
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    public static String getProperty(String property) {
        return getUtil().getProp(property);
    }
}


2、ImportUtil.java工具类,支持2003和2007不同格式excel文件。

  1. package org.nercita.bcp.util;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.text.DecimalFormat;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.ArrayList;  
  9. import java.util.Arrays;  
  10. import java.util.Date;  
  11. import java.util.List;  
  12.   
  13. import org.apache.poi.hssf.usermodel.HSSFCell;  
  14. import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
  15. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  16. import org.apache.poi.ss.usermodel.Cell;  
  17. import org.apache.poi.ss.usermodel.Row;  
  18. import org.apache.poi.ss.usermodel.Sheet;  
  19. import org.apache.poi.ss.usermodel.Workbook;  
  20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  21. import org.springframework.web.multipart.MultipartFile;  
  22.   
  23. /**  
  24.  * excel文件导入工具类  
  25.  */  
  26. public class ImportUtil {  
  27.       
  28.     public static String EXCEL_2007_ContentType = “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”;  
  29.     public static String EXCEL_2003_ContentType = “application/vnd.ms-excel”;  
  30.       
  31.     /**  
  32.      * excel文件导入  
  33.      * @param file  
  34.      * @param ignoreRows 需要忽略掉的行数  
  35.      * @return  
  36.      * @throws FileNotFoundException  
  37.      * @throws IOException  
  38.      */  
  39.     public static String[][] importFile(MultipartFile file, int ignoreRows) throws FileNotFoundException, IOException {  
  40.         List<String[]> result = new ArrayList<String[]>();  
  41.         String contentType = file.getContentType();  //内容类型   
  42.         InputStream stream = file.getInputStream();  //输入流  
  43.         Workbook wb=null;  
  44.         //根据inputStream建立一个Excel对象  
  45.         if (EXCEL_2003_ContentType.equals(contentType)){  
  46.             wb =(Workbook) new HSSFWorkbook(stream);    //2003  
  47.         }else if(EXCEL_2007_ContentType.equals(contentType)) {  
  48.             wb =(Workbook) new XSSFWorkbook(stream);    //2007  
  49.         }  
  50.         int rowSize = 0;  
  51.         Cell cell = null;  
  52.         for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {  
  53.             Sheet st = wb.getSheetAt(sheetIndex);  
  54.             for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {  
  55.                 Row row = st.getRow(rowIndex);  
  56.                 if (null == row) {  
  57.                     continue;  
  58.                 }  
  59.                 int tempRowSize = row.getLastCellNum() + 1;  
  60.                 if (tempRowSize > rowSize) {  
  61.                     rowSize = tempRowSize;  
  62.                 }  
  63.                 String[] values = new String[rowSize];  
  64.                 Arrays.fill(values, ”“);  
  65.                 boolean hasValue = false;  
  66.                 for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {  
  67.                     String value = “”;  
  68.                     cell = row.getCell(columnIndex);  
  69.                     if (null != cell) {  
  70.                         switch (cell.getCellType()) {  
  71.                         case HSSFCell.CELL_TYPE_STRING:  
  72.                             value = cell.getStringCellValue();  
  73.                             break;  
  74.                         case HSSFCell.CELL_TYPE_NUMERIC:  
  75.                             if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  76.                                 Date date = cell.getDateCellValue();  
  77.                                 if (null != date) {  
  78.                                     value = new SimpleDateFormat(“yyyy-MM-dd”).format(date);  
  79.                                 } else {  
  80.                                     value = “”;  
  81.                                 }  
  82.                             } else {  
  83.                                 DecimalFormat df = new DecimalFormat(“0.#######”);                                      
  84.                                 //value = df.format(cell.getNumericCellValue());                                  
  85.                                 value = String.valueOf(df.format(cell.getNumericCellValue()));  
  86.                             }  
  87.                             break;  
  88.                         case HSSFCell.CELL_TYPE_FORMULA:  
  89.                             // 公式生成的数据  
  90.                             if (!”“.equals(cell.getStringCellValue())) {  
  91.                                 value = cell.getStringCellValue();  
  92.                             } else {  
  93.                                 value = cell.getNumericCellValue() + ”“;  
  94.                             }  
  95.                             break;  
  96.                         case HSSFCell.CELL_TYPE_BLANK:  
  97.                             break;  
  98.                         case HSSFCell.CELL_TYPE_ERROR:  
  99.                             value = “”;  
  100.                             break;  
  101.                         case HSSFCell.CELL_TYPE_BOOLEAN:  
  102.                             value = (cell.getBooleanCellValue() == true ? “Y” : “N”);  
  103.                             break;  
  104.                         default:  
  105.                             value = “”;  
  106.                         }  
  107.                     }  
  108.                     if (columnIndex == 0 && value.trim().equals(“”)) {  
  109.                         break;  
  110.                     }  
  111.                     values[columnIndex] = rightTrim(value);  
  112.                     hasValue = true;  
  113.                     }  
  114.                 if (hasValue) {  
  115.                     result.add(values);  
  116.                 }  
  117.             }  
  118.         }  
  119.         stream.close();  
  120.         String[][] returnArray = new String[result.size()][rowSize];  
  121.         for (int i = 0; i < returnArray.length; i++) {  
  122.             returnArray[i] = (String[]) result.get(i);  
  123.         }  
  124.         return returnArray;  
  125.     }  
  126.       
  127.     /**  
  128.      * excel文件导入  
  129.      * @param file  
  130.      * @param ignoreRows 需要忽略掉的行数  
  131.      * @return  
  132.      * @throws FileNotFoundException  
  133.      * @throws IOException  
  134.      */  
  135.     public static String[][] importFile(MultipartFile file,int sheetIndex, int ignoreRows,Integer colCnt) throws FileNotFoundException, IOException {  
  136.         List<String[]> result = new ArrayList<String[]>();  
  137.         String contentType = file.getContentType();  //内容类型   
  138.         InputStream stream = file.getInputStream();  //输入流  
  139.         Workbook wb=null;  
  140.         //根据inputStream建立一个Excel对象  
  141.         if (EXCEL_2003_ContentType.equals(contentType)){  
  142.             wb =(Workbook) new HSSFWorkbook(stream);    //2003  
  143.         }else if(EXCEL_2007_ContentType.equals(contentType)) {  
  144.             wb =(Workbook) new XSSFWorkbook(stream);    //2007  
  145.         }  
  146.         int rowSize = 0;  
  147.         Cell cell = null;  
  148.   
  149.         Sheet st = wb.getSheetAt(sheetIndex);  
  150.         for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {  
  151.             Row row = st.getRow(rowIndex);  
  152.             if (null == row) {  
  153.                 continue;  
  154.             }  
  155. //          int tempRowSize = row.getLastCellNum() + 1;  
  156.             int tempRowSize = row.getPhysicalNumberOfCells();  
  157.               
  158.             if(colCnt==null){  
  159.                 if (tempRowSize > rowSize) {  
  160.                     rowSize = tempRowSize;  
  161.                 }  
  162.                 colCnt=rowSize;  
  163.             }  
  164.             String[] values = new String[colCnt];  
  165.             Arrays.fill(values, ”“);  
  166.             boolean hasValue = false;  
  167.             for (short columnIndex = 0; columnIndex < colCnt; columnIndex++) {  
  168.                 String value = “”;  
  169.                 cell = row.getCell(columnIndex);  
  170.                 if (null != cell) {  
  171.                     switch (cell.getCellType()) {  
  172.                     case HSSFCell.CELL_TYPE_STRING:  
  173.                         value = cell.getStringCellValue();  
  174.                         break;  
  175.                     case HSSFCell.CELL_TYPE_NUMERIC:  
  176.                         if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  177.                             Date date = cell.getDateCellValue();  
  178.                             if (null != date) {  
  179.                                 value = new SimpleDateFormat(“yyyy-MM-dd”).format(date);  
  180.                             } else {  
  181.                                 value = “”;  
  182.                             }  
  183.                         } else {  
  184.                             DecimalFormat df = new DecimalFormat(“0.#######”);                                      
  185.                             //value = df.format(cell.getNumericCellValue());                                  
  186.                             value = String.valueOf(df.format(cell.getNumericCellValue()));  
  187.                         }  
  188.                         break;  
  189.                     case HSSFCell.CELL_TYPE_FORMULA:  
  190.                         // 公式生成的数据  
  191.                         if (!”“.equals(cell.getStringCellValue())) {  
  192.                             value = cell.getStringCellValue();  
  193.                         } else {  
  194.                             value = cell.getNumericCellValue() + ”“;  
  195.                         }  
  196.                         break;  
  197.                     case HSSFCell.CELL_TYPE_BLANK:  
  198.                         break;  
  199.                     case HSSFCell.CELL_TYPE_ERROR:  
  200.                         value = “”;  
  201.                         break;  
  202.                     case HSSFCell.CELL_TYPE_BOOLEAN:  
  203.                         value = (cell.getBooleanCellValue() == true ? “Y” : “N”);  
  204.                         break;  
  205.                     default:  
  206.                         value = “”;  
  207.                     }  
  208.                 }  
  209.                 if (columnIndex == 0 && value.trim().equals(“”)) {  
  210.                     break;  
  211.                 }  
  212.                 values[columnIndex] = rightTrim(value);  
  213.                 hasValue = true;  
  214.                 }  
  215.             if (hasValue) {  
  216.                 result.add(values);  
  217.             }  
  218.         }  
  219.               
  220.         stream.close();  
  221.         String[][] returnArray = new String[result.size()][colCnt];  
  222.         for (int i = 0; i < returnArray.length; i++) {  
  223.             returnArray[i] = (String[]) result.get(i);  
  224.         }  
  225.         return returnArray;  
  226.     }  
  227.       
  228.     /**  
  229.      * 去除字符串右侧空格(直接使用trim()将不能支持中间存在空格的单元格)  
  230.      * @param str  
  231.      * @return  
  232.      */  
  233.     public static String rightTrim(String str) {  
  234.         if (str == null) {  
  235.             return ”“;  
  236.         }  
  237.         int length = str.length();  
  238.         for (int i = length - 1; i >= 0; i–) {  
  239.             if (0x20 != str.charAt(i)) {  
  240.                 break;  
  241.             }  
  242.             length–;  
  243.         }  
  244.         return str.substring(0, length);  
  245.     }  
  246. }  
package org.nercita.bcp.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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 org.springframework.web.multipart.MultipartFile;

/**
 * excel文件导入工具类
 */
public class ImportUtil {

    public static String EXCEL_2007_ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    public static String EXCEL_2003_ContentType = "application/vnd.ms-excel";

    /**
     * excel文件导入
     * @param file
     * @param ignoreRows 需要忽略掉的行数
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String[][] importFile(MultipartFile file, int ignoreRows) throws FileNotFoundException, IOException {
        List<String[]> result = new ArrayList<String[]>();
        String contentType = file.getContentType();  //内容类型 
        InputStream stream = file.getInputStream();  //输入流
        Workbook wb=null;
        //根据inputStream建立一个Excel对象
        if (EXCEL_2003_ContentType.equals(contentType)){
            wb =(Workbook) new HSSFWorkbook(stream);    //2003
        }else if(EXCEL_2007_ContentType.equals(contentType)) {
            wb =(Workbook) new XSSFWorkbook(stream);    //2007
        }
        int rowSize = 0;
        Cell cell = null;
        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            Sheet st = wb.getSheetAt(sheetIndex);
            for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
                Row row = st.getRow(rowIndex);
                if (null == row) {
                    continue;
                }
                int tempRowSize = row.getLastCellNum() + 1;
                if (tempRowSize > rowSize) {
                    rowSize = tempRowSize;
                }
                String[] values = new String[rowSize];
                Arrays.fill(values, "");
                boolean hasValue = false;
                for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
                    String value = "";
                    cell = row.getCell(columnIndex);
                    if (null != cell) {
                        switch (cell.getCellType()) {
                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getStringCellValue();
                            break;
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                Date date = cell.getDateCellValue();
                                if (null != date) {
                                    value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                                } else {
                                    value = "";
                                }
                            } else {
                                DecimalFormat df = new DecimalFormat("0.#######");                                    
                                //value = df.format(cell.getNumericCellValue());                                
                                value = String.valueOf(df.format(cell.getNumericCellValue()));
                            }
                            break;
                        case HSSFCell.CELL_TYPE_FORMULA:
                            // 公式生成的数据
                            if (!"".equals(cell.getStringCellValue())) {
                                value = cell.getStringCellValue();
                            } else {
                                value = cell.getNumericCellValue() + "";
                            }
                            break;
                        case HSSFCell.CELL_TYPE_BLANK:
                            break;
                        case HSSFCell.CELL_TYPE_ERROR:
                            value = "";
                            break;
                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            value = (cell.getBooleanCellValue() == true ? "Y" : "N");
                            break;
                        default:
                            value = "";
                        }
                    }
                    if (columnIndex == 0 && value.trim().equals("")) {
                        break;
                    }
                    values[columnIndex] = rightTrim(value);
                    hasValue = true;
                    }
                if (hasValue) {
                    result.add(values);
                }
            }
        }
        stream.close();
        String[][] returnArray = new String[result.size()][rowSize];
        for (int i = 0; i < returnArray.length; i++) {
            returnArray[i] = (String[]) result.get(i);
        }
        return returnArray;
    }

    /**
     * excel文件导入
     * @param file
     * @param ignoreRows 需要忽略掉的行数
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String[][] importFile(MultipartFile file,int sheetIndex, int ignoreRows,Integer colCnt) throws FileNotFoundException, IOException {
        List<String[]> result = new ArrayList<String[]>();
        String contentType = file.getContentType();  //内容类型 
        InputStream stream = file.getInputStream();  //输入流
        Workbook wb=null;
        //根据inputStream建立一个Excel对象
        if (EXCEL_2003_ContentType.equals(contentType)){
            wb =(Workbook) new HSSFWorkbook(stream);    //2003
        }else if(EXCEL_2007_ContentType.equals(contentType)) {
            wb =(Workbook) new XSSFWorkbook(stream);    //2007
        }
        int rowSize = 0;
        Cell cell = null;

        Sheet st = wb.getSheetAt(sheetIndex);
        for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
            Row row = st.getRow(rowIndex);
            if (null == row) {
                continue;
            }
//          int tempRowSize = row.getLastCellNum() + 1;
            int tempRowSize = row.getPhysicalNumberOfCells();

            if(colCnt==null){
                if (tempRowSize > rowSize) {
                    rowSize = tempRowSize;
                }
                colCnt=rowSize;
            }
            String[] values = new String[colCnt];
            Arrays.fill(values, "");
            boolean hasValue = false;
            for (short columnIndex = 0; columnIndex < colCnt; columnIndex++) {
                String value = "";
                cell = row.getCell(columnIndex);
                if (null != cell) {
                    switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_STRING:
                        value = cell.getStringCellValue();
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            Date date = cell.getDateCellValue();
                            if (null != date) {
                                value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                            } else {
                                value = "";
                            }
                        } else {
                            DecimalFormat df = new DecimalFormat("0.#######");                                    
                            //value = df.format(cell.getNumericCellValue());                                
                            value = String.valueOf(df.format(cell.getNumericCellValue()));
                        }
                        break;
                    case HSSFCell.CELL_TYPE_FORMULA:
                        // 公式生成的数据
                        if (!"".equals(cell.getStringCellValue())) {
                            value = cell.getStringCellValue();
                        } else {
                            value = cell.getNumericCellValue() + "";
                        }
                        break;
                    case HSSFCell.CELL_TYPE_BLANK:
                        break;
                    case HSSFCell.CELL_TYPE_ERROR:
                        value = "";
                        break;
                    case HSSFCell.CELL_TYPE_BOOLEAN:
                        value = (cell.getBooleanCellValue() == true ? "Y" : "N");
                        break;
                    default:
                        value = "";
                    }
                }
                if (columnIndex == 0 && value.trim().equals("")) {
                    break;
                }
                values[columnIndex] = rightTrim(value);
                hasValue = true;
                }
            if (hasValue) {
                result.add(values);
            }
        }

        stream.close();
        String[][] returnArray = new String[result.size()][colCnt];
        for (int i = 0; i < returnArray.length; i++) {
            returnArray[i] = (String[]) result.get(i);
        }
        return returnArray;
    }

    /**
     * 去除字符串右侧空格(直接使用trim()将不能支持中间存在空格的单元格)
     * @param str
     * @return
     */
    public static String rightTrim(String str) {
        if (str == null) {
            return "";
        }
        int length = str.length();
        for (int i = length - 1; i >= 0; i--) {
            if (0x20 != str.charAt(i)) {
                break;
            }
            length--;
        }
        return str.substring(0, length);
    }
}


 

1、ExportUtil导出工具类(根据模板导出),支持2003/2007不同excel格式文件

  1. package org.nercita.bcp.util;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.net.URLEncoder;  
  7. import java.util.Iterator;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10. import java.util.Properties;  
  11.   
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. import net.sf.jxls.transformer.XLSTransformer;  
  16.   
  17. import org.apache.commons.io.IOUtils;  
  18. import org.apache.commons.lang.StringUtils;  
  19. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  20. import org.apache.poi.hssf.usermodel.HSSFFont;  
  21. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  22. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
  23. import org.apache.poi.ss.usermodel.Cell;  
  24. import org.apache.poi.ss.usermodel.Row;  
  25. import org.apache.poi.ss.usermodel.Sheet;  
  26. import org.apache.poi.ss.usermodel.Workbook;  
  27. import org.apache.poi.ss.util.CellRangeAddress;  
  28. import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
  29. import org.apache.poi.xssf.usermodel.XSSFFont;  
  30. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  31. import org.springframework.core.io.ClassPathResource;  
  32. import org.springframework.util.Assert;  
  33.   
  34. /**  
  35.  * 导出工具类  
  36.  */  
  37. public class ExportUtil {  
  38.     public static String EXCEL_2007 = “Excel2007”;  
  39.     public static String EXCEL_2003 = “Excel2003”;  
  40.     private volatile Properties props = new Properties();  
  41.     private boolean inited = false;  
  42.     private volatile static ExportUtil util = new ExportUtil();  
  43.   
  44.     private ExportUtil() {  
  45.         init();  
  46.     }  
  47.   
  48.     public Properties getProps() {  
  49.         if (!inited)  
  50.             init();  
  51.         return props;  
  52.     }  
  53.   
  54.     public String getProp(String key) {  
  55.         if (!inited)  
  56.             init();  
  57.         return props.getProperty(key);  
  58.     }  
  59.   
  60.     public String getProp(String key, String defaultValue) {  
  61.         if (!inited)  
  62.             init();  
  63.         return props.getProperty(key, defaultValue);  
  64.     }  
  65.   
  66.   
  67.     private void init() {  
  68.         try {  
  69.             InputStream is = new ClassPathResource(“export.properties”).getInputStream();  
  70.             props.load(is);  
  71.             is.close();  
  72.             inited = true;  
  73.         } catch (IOException e) {  
  74.             e.printStackTrace();  
  75.         }  
  76.     }  
  77.   
  78.     public static ExportUtil getUtil() {  
  79.         if (util == null)  
  80.             util = new ExportUtil();  
  81.         return util;  
  82.     }  
  83.   
  84.     /**  
  85.      * 设置下载文件中文件的名称  
  86.      *  
  87.      * @param pFileName  
  88.      * @param request  
  89.      * @return  
  90.      */  
  91.     public static String encodeFilename(String pFileName, HttpServletRequest request){  
  92.         String filename = null;      
  93.         String agent = request.getHeader(“USER-AGENT”);  
  94.         try {  
  95.                   
  96.             if (null != agent){      
  97.                 if (-1 != agent.indexOf(“Firefox”)) {//Firefox      
  98.                     filename = “=?UTF-8?B?” + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes(“UTF-8”))))+ ”?=”;      
  99.                 }else if (-1 != agent.indexOf(“Chrome”)) {//Chrome      
  100.                     filename = new String(pFileName.getBytes(), “ISO8859-1”);      
  101.                 } else {//IE7+      
  102.                     filename = URLEncoder.encode(pFileName, “UTF-8”);      
  103.                     filename = StringUtils.replace(filename, ”+”, ”%20”);//替换空格      
  104.                 }      
  105.             } else {      
  106.                 filename = pFileName;      
  107.             }      
  108.              
  109.         } catch (Exception ex) {  
  110.   
  111.         }  
  112.          return filename;  
  113.    }  
  114.   
  115.     //导出  
  116.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response,   
  117.             String version, String templatePath, Map<String, Object> beanParams,Map<Integer,List<CellFill>> mapFill) {  
  118.         writeResponse(fileName, request, response, version, templatePath, beanParams, false, null, null, mapFill);  
  119.     }  
  120.       
  121.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response,   
  122.             String version, String templatePath, Map<String, Object> beanParams) {  
  123.         writeResponse(fileName, request, response, version, templatePath, beanParams, false, null, null, null);  
  124.     }  
  125.   
  126.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,  
  127.                                      boolean innerCollectionAccess) {  
  128.         writeResponse(fileName, request, response, version, templatePath, beanParams, innerCollectionAccess, null, null, null);  
  129.     }  
  130.   
  131.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,  
  132.                                      boolean innerCollectionAccess, Map<Integer, List<CellRangeAddress>> rangeMap) {  
  133.         writeResponse(fileName, request, response, version, templatePath, beanParams, innerCollectionAccess, rangeMap, null, null);  
  134.     }  
  135.   
  136.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,  
  137.                                      Map<Integer, List<CellRangeAddress>> rangeMap, XLSTransformer transformer) {  
  138.         writeResponse(fileName, request, response, version, templatePath, beanParams, false, rangeMap, transformer, null);  
  139.     }  
  140.   
  141.     //  
  142.     public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response,   
  143.             String version, String templatePath, Map<String, Object> beanParams,  
  144.             boolean innerCollectionAccess, Map<Integer, List<CellRangeAddress>> rangeMap, XLSTransformer trans,  
  145.             Map<Integer,List<CellFill>> mapFill) {  
  146.         Assert.isTrue(StringUtils.isNotBlank(templatePath), “templatePath不可以为空字符串”);  
  147.         XLSTransformer transformer = null;  
  148.         if (trans != null) {  
  149.             transformer = trans;  
  150.         } else {  
  151.             transformer = new XLSTransformer();  
  152.         }  
  153.         transformer.setJexlInnerCollectionsAccess(innerCollectionAccess);  
  154.         response.setCharacterEncoding(“utf-8”);  
  155.         if (EXCEL_2007.equals(version)) {  
  156.             fileName = encodeFilename(fileName + ”.xlsx”, request);  
  157.             response.setContentType(“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8”);  
  158.         } else {  
  159.             fileName = encodeFilename(fileName + ”.xls”, request);  
  160.             response.setContentType(“application/vnd.ms-excel;charset=UTF-8”);  
  161.         }  
  162.         response.setHeader(“Content-Disposition”, “attachment;fileName=” + fileName);  
  163.         InputStream is = null;  
  164.         try {  
  165.             if(“linux”.equals(System.getProperty(“os.name”).toLowerCase())){  
  166.                 if(!templatePath.startsWith(“/”)){  
  167.                     templatePath=“/”+templatePath;  
  168.                 }  
  169.             }  
  170.             is = new FileInputStream(templatePath);  
  171.             Workbook book = transformer.transformXLS(is, beanParams);  
  172.             if (rangeMap != null) {  
  173.                 Iterator<Integer> index = rangeMap.keySet().iterator();  
  174.                 while (index.hasNext()) {  
  175.                     Integer i = index.next();  
  176.                     Sheet sheet = book.getSheetAt(i);  
  177.                     Iterator<CellRangeAddress> cra = rangeMap.get(i).iterator();  
  178.                     while (cra.hasNext()) {  
  179.                         sheet.addMergedRegion(cra.next());  
  180.                     }  
  181.                 }  
  182.             }  
  183.               
  184.             //==========填充颜色,add by psh   
  185.            if(mapFill!=null) {  
  186.                if (EXCEL_2003.equals(version)) {  
  187.                    HSSFWorkbook workbook=(HSSFWorkbook)book;  
  188.                    Iterator<Integer> sheetIndex = mapFill.keySet().iterator();  
  189.                    while (sheetIndex.hasNext()) {  
  190.                        Integer index = sheetIndex.next();  
  191.                        Sheet sheet = workbook.getSheetAt(index);  
  192.                        List<CellFill> list = mapFill.get(index);  
  193.                        CellFill cellFillnull;  
  194.                        for(int i=0;i<list.size();i++){  
  195.                            cellFilllist.get(i);  
  196.                            Row row = (Row)sheet.getRow(cellFill.getRow());  
  197.                            if(row==null){  
  198.                                continue;  
  199.                            }  
  200.                            Cell cell = row.getCell(cellFill.getCol());  
  201.                            if(cell==null){  
  202.                                continue;  
  203.                            }  
  204.                            HSSFCellStyle sheetStyle = workbook.createCellStyle();     //Sheet样式  
  205.                            sheetStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //填充模式  
  206.                            sheetStyle.setFillForegroundColor(cellFill.getBgColor()); //前景色(单元格)的设定。HSSFColor.YELLOW.index——黄色  
  207.                            HSSFFont font=workbook.createFont();  
  208.                            font.setColor(cellFill.getFontColor());  
  209.                            sheetStyle.setFont(font);                   
  210.                            cell.setCellStyle(sheetStyle);  
  211.                        }  
  212.                    }//end while  
  213.                }else {  
  214.                    XSSFWorkbook workbook=(XSSFWorkbook)book;  
  215.                    Iterator<Integer> sheetIndex = mapFill.keySet().iterator();  
  216.                    while (sheetIndex.hasNext()) {  
  217.                        Integer index = sheetIndex.next();  
  218.                        Sheet sheet = workbook.getSheetAt(index);  
  219.                        List<CellFill> list = mapFill.get(index);  
  220.                        CellFill cellFillnull;  
  221.                        for(int i=0;i<list.size();i++){  
  222.                            cellFilllist.get(i);  
  223.                            Row row = (Row)sheet.getRow(cellFill.getRow());  
  224.                            if(row==null){  
  225.                                continue;  
  226.                            }  
  227.                            Cell cell = row.getCell(cellFill.getCol());  
  228.                            if(cell==null){  
  229.                                continue;  
  230.                            }  
  231.                            XSSFCellStyle sheetStyle = workbook.createCellStyle();     //Sheet样式  
  232.                            sheetStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //填充模式  
  233.                            sheetStyle.setFillForegroundColor(cellFill.getBgColor()); //前景色(单元格)的设定。HSSFColor.YELLOW.index——黄色  
  234.                            XSSFFont font=workbook.createFont();  
  235.                            font.setColor(cellFill.getFontColor());  
  236.                            sheetStyle.setFont(font);                   
  237.                            cell.setCellStyle(sheetStyle);  
  238.                        }  
  239.                    }//end while  
  240.                } //end 2007          
  241.            }             
  242.            //=====end 颜色===========  
  243.               
  244.            book.write(response.getOutputStream());                    
  245.         } catch (IOException e) {  
  246.             e.printStackTrace();  
  247.         } catch (InvalidFormatException e) {  
  248.             e.printStackTrace();  
  249.         } finally {  
  250.             IOUtils.closeQuietly(is);  
  251.         }  
  252.     }  
  253.   
  254.     public static String getProperty(String property) {  
  255.         return getUtil().getProp(property);  
  256.     }  
  257. }  
package org.nercita.bcp.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;

/**
 * 导出工具类
 */
public class ExportUtil {
    public static String EXCEL_2007 = "Excel2007";
    public static String EXCEL_2003 = "Excel2003";
    private volatile Properties props = new Properties();
    private boolean inited = false;
    private volatile static ExportUtil util = new ExportUtil();

    private ExportUtil() {
        init();
    }

    public Properties getProps() {
        if (!inited)
            init();
        return props;
    }

    public String getProp(String key) {
        if (!inited)
            init();
        return props.getProperty(key);
    }

    public String getProp(String key, String defaultValue) {
        if (!inited)
            init();
        return props.getProperty(key, defaultValue);
    }


    private void init() {
        try {
            InputStream is = new ClassPathResource("export.properties").getInputStream();
            props.load(is);
            is.close();
            inited = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ExportUtil getUtil() {
        if (util == null)
            util = new ExportUtil();
        return util;
    }

    /**
     * 设置下载文件中文件的名称
     *
     * @param pFileName
     * @param request
     * @return
     */
    public static String encodeFilename(String pFileName, HttpServletRequest request){
        String filename = null;    
        String agent = request.getHeader("USER-AGENT");
        try {

            if (null != agent){    
                if (-1 != agent.indexOf("Firefox")) {//Firefox    
                    filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8"))))+ "?=";    
                }else if (-1 != agent.indexOf("Chrome")) {//Chrome    
                    filename = new String(pFileName.getBytes(), "ISO8859-1");    
                } else {//IE7+    
                    filename = URLEncoder.encode(pFileName, "UTF-8");    
                    filename = StringUtils.replace(filename, "+", "%20");//替换空格    
                }    
            } else {    
                filename = pFileName;    
            }    

        } catch (Exception ex) {

        }
         return filename;
   }

    //导出
    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, 
            String version, String templatePath, Map<String, Object> beanParams,Map<Integer,List<CellFill>> mapFill) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, false, null, null, mapFill);
    }

    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, 
            String version, String templatePath, Map<String, Object> beanParams) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, false, null, null, null);
    }

    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,
                                     boolean innerCollectionAccess) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, innerCollectionAccess, null, null, null);
    }

    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,
                                     boolean innerCollectionAccess, Map<Integer, List<CellRangeAddress>> rangeMap) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, innerCollectionAccess, rangeMap, null, null);
    }

    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, String version, String templatePath, Map<String, Object> beanParams,
                                     Map<Integer, List<CellRangeAddress>> rangeMap, XLSTransformer transformer) {
        writeResponse(fileName, request, response, version, templatePath, beanParams, false, rangeMap, transformer, null);
    }

    //
    public static void writeResponse(String fileName, HttpServletRequest request, HttpServletResponse response, 
            String version, String templatePath, Map<String, Object> beanParams,
            boolean innerCollectionAccess, Map<Integer, List<CellRangeAddress>> rangeMap, XLSTransformer trans,
            Map<Integer,List<CellFill>> mapFill) {
        Assert.isTrue(StringUtils.isNotBlank(templatePath), "templatePath不可以为空字符串");
        XLSTransformer transformer = null;
        if (trans != null) {
            transformer = trans;
        } else {
            transformer = new XLSTransformer();
        }
        transformer.setJexlInnerCollectionsAccess(innerCollectionAccess);
        response.setCharacterEncoding("utf-8");
        if (EXCEL_2007.equals(version)) {
            fileName = encodeFilename(fileName + ".xlsx", request);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        } else {
            fileName = encodeFilename(fileName + ".xls", request);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        InputStream is = null;
        try {
            if("linux".equals(System.getProperty("os.name").toLowerCase())){
                if(!templatePath.startsWith("/")){
                    templatePath="/"+templatePath;
                }
            }
            is = new FileInputStream(templatePath);
            Workbook book = transformer.transformXLS(is, beanParams);
            if (rangeMap != null) {
                Iterator<Integer> index = rangeMap.keySet().iterator();
                while (index.hasNext()) {
                    Integer i = index.next();
                    Sheet sheet = book.getSheetAt(i);
                    Iterator<CellRangeAddress> cra = rangeMap.get(i).iterator();
                    while (cra.hasNext()) {
                        sheet.addMergedRegion(cra.next());
                    }
                }
            }

            //==========填充颜色,add by psh 
           if(mapFill!=null) {
               if (EXCEL_2003.equals(version)) {
                   HSSFWorkbook workbook=(HSSFWorkbook)book;
                   Iterator<Integer> sheetIndex = mapFill.keySet().iterator();
                   while (sheetIndex.hasNext()) {
                       Integer index = sheetIndex.next();
                       Sheet sheet = workbook.getSheetAt(index);
                       List<CellFill> list = mapFill.get(index);
                       CellFill cellFill= null;
                       for(int i=0;i<list.size();i++){
                           cellFill= list.get(i);
                           Row row = (Row)sheet.getRow(cellFill.getRow());
                           if(row==null){
                               continue;
                           }
                           Cell cell = row.getCell(cellFill.getCol());
                           if(cell==null){
                               continue;
                           }
                           HSSFCellStyle sheetStyle = workbook.createCellStyle();     //Sheet样式
                           sheetStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //填充模式
                           sheetStyle.setFillForegroundColor(cellFill.getBgColor()); //前景色(单元格)的设定。HSSFColor.YELLOW.index——黄色
                           HSSFFont font=workbook.createFont();
                           font.setColor(cellFill.getFontColor());
                           sheetStyle.setFont(font);                 
                           cell.setCellStyle(sheetStyle);
                       }
                   }//end while
               }else {
                   XSSFWorkbook workbook=(XSSFWorkbook)book;
                   Iterator<Integer> sheetIndex = mapFill.keySet().iterator();
                   while (sheetIndex.hasNext()) {
                       Integer index = sheetIndex.next();
                       Sheet sheet = workbook.getSheetAt(index);
                       List<CellFill> list = mapFill.get(index);
                       CellFill cellFill= null;
                       for(int i=0;i<list.size();i++){
                           cellFill= list.get(i);
                           Row row = (Row)sheet.getRow(cellFill.getRow());
                           if(row==null){
                               continue;
                           }
                           Cell cell = row.getCell(cellFill.getCol());
                           if(cell==null){
                               continue;
                           }
                           XSSFCellStyle sheetStyle = workbook.createCellStyle();     //Sheet样式
                           sheetStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //填充模式
                           sheetStyle.setFillForegroundColor(cellFill.getBgColor()); //前景色(单元格)的设定。HSSFColor.YELLOW.index——黄色
                           XSSFFont font=workbook.createFont();
                           font.setColor(cellFill.getFontColor());
                           sheetStyle.setFont(font);                 
                           cell.setCellStyle(sheetStyle);
                       }
                   }//end while
               } //end 2007        
           }           
           //=====end 颜色===========

           book.write(response.getOutputStream());                  
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    public static String getProperty(String property) {
        return getUtil().getProp(property);
    }
}


2、ImportUtil.java工具类,支持2003和2007不同格式excel文件。

  1. package org.nercita.bcp.util;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.text.DecimalFormat;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.ArrayList;  
  9. import java.util.Arrays;  
  10. import java.util.Date;  
  11. import java.util.List;  
  12.   
  13. import org.apache.poi.hssf.usermodel.HSSFCell;  
  14. import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
  15. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  16. import org.apache.poi.ss.usermodel.Cell;  
  17. import org.apache.poi.ss.usermodel.Row;  
  18. import org.apache.poi.ss.usermodel.Sheet;  
  19. import org.apache.poi.ss.usermodel.Workbook;  
  20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  21. import org.springframework.web.multipart.MultipartFile;  
  22.   
  23. /**  
  24.  * excel文件导入工具类  
  25.  */  
  26. public class ImportUtil {  
  27.       
  28.     public static String EXCEL_2007_ContentType = “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”;  
  29.     public static String EXCEL_2003_ContentType = “application/vnd.ms-excel”;  
  30.       
  31.     /**  
  32.      * excel文件导入  
  33.      * @param file  
  34.      * @param ignoreRows 需要忽略掉的行数  
  35.      * @return  
  36.      * @throws FileNotFoundException  
  37.      * @throws IOException  
  38.      */  
  39.     public static String[][] importFile(MultipartFile file, int ignoreRows) throws FileNotFoundException, IOException {  
  40.         List<String[]> result = new ArrayList<String[]>();  
  41.         String contentType = file.getContentType();  //内容类型   
  42.         InputStream stream = file.getInputStream();  //输入流  
  43.         Workbook wb=null;  
  44.         //根据inputStream建立一个Excel对象  
  45.         if (EXCEL_2003_ContentType.equals(contentType)){  
  46.             wb =(Workbook) new HSSFWorkbook(stream);    //2003  
  47.         }else if(EXCEL_2007_ContentType.equals(contentType)) {  
  48.             wb =(Workbook) new XSSFWorkbook(stream);    //2007  
  49.         }  
  50.         int rowSize = 0;  
  51.         Cell cell = null;  
  52.         for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {  
  53.             Sheet st = wb.getSheetAt(sheetIndex);  
  54.             for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {  
  55.                 Row row = st.getRow(rowIndex);  
  56.                 if (null == row) {  
  57.                     continue;  
  58.                 }  
  59.                 int tempRowSize = row.getLastCellNum() + 1;  
  60.                 if (tempRowSize > rowSize) {  
  61.                     rowSize = tempRowSize;  
  62.                 }  
  63.                 String[] values = new String[rowSize];  
  64.                 Arrays.fill(values, ”“);  
  65.                 boolean hasValue = false;  
  66.                 for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {  
  67.                     String value = “”;  
  68.                     cell = row.getCell(columnIndex);  
  69.                     if (null != cell) {  
  70.                         switch (cell.getCellType()) {  
  71.                         case HSSFCell.CELL_TYPE_STRING:  
  72.                             value = cell.getStringCellValue();  
  73.                             break;  
  74.                         case HSSFCell.CELL_TYPE_NUMERIC:  
  75.                             if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  76.                                 Date date = cell.getDateCellValue();  
  77.                                 if (null != date) {  
  78.                                     value = new SimpleDateFormat(“yyyy-MM-dd”).format(date);  
  79.                                 } else {  
  80.                                     value = “”;  
  81.                                 }  
  82.                             } else {  
  83.                                 DecimalFormat df = new DecimalFormat(“0.#######”);                                      
  84.                                 //value = df.format(cell.getNumericCellValue());                                  
  85.                                 value = String.valueOf(df.format(cell.getNumericCellValue()));  
  86.                             }  
  87.                             break;  
  88.                         case HSSFCell.CELL_TYPE_FORMULA:  
  89.                             // 公式生成的数据  
  90.                             if (!”“.equals(cell.getStringCellValue())) {  
  91.                                 value = cell.getStringCellValue();  
  92.                             } else {  
  93.                                 value = cell.getNumericCellValue() + ”“;  
  94.                             }  
  95.                             break;  
  96.                         case HSSFCell.CELL_TYPE_BLANK:  
  97.                             break;  
  98.                         case HSSFCell.CELL_TYPE_ERROR:  
  99.                             value = “”;  
  100.                             break;  
  101.                         case HSSFCell.CELL_TYPE_BOOLEAN:  
  102.                             value = (cell.getBooleanCellValue() == true ? “Y” : “N”);  
  103.                             break;  
  104.                         default:  
  105.                             value = “”;  
  106.                         }  
  107.                     }  
  108.                     if (columnIndex == 0 && value.trim().equals(“”)) {  
  109.                         break;  
  110.                     }  
  111.                     values[columnIndex] = rightTrim(value);  
  112.                     hasValue = true;  
  113.                     }  
  114.                 if (hasValue) {  
  115.                     result.add(values);  
  116.                 }  
  117.             }  
  118.         }  
  119.         stream.close();  
  120.         String[][] returnArray = new String[result.size()][rowSize];  
  121.         for (int i = 0; i < returnArray.length; i++) {  
  122.             returnArray[i] = (String[]) result.get(i);  
  123.         }  
  124.         return returnArray;  
  125.     }  
  126.       
  127.     /**  
  128.      * excel文件导入  
  129.      * @param file  
  130.      * @param ignoreRows 需要忽略掉的行数  
  131.      * @return  
  132.      * @throws FileNotFoundException  
  133.      * @throws IOException  
  134.      */  
  135.     public static String[][] importFile(MultipartFile file,int sheetIndex, int ignoreRows,Integer colCnt) throws FileNotFoundException, IOException {  
  136.         List<String[]> result = new ArrayList<String[]>();  
  137.         String contentType = file.getContentType();  //内容类型   
  138.         InputStream stream = file.getInputStream();  //输入流  
  139.         Workbook wb=null;  
  140.         //根据inputStream建立一个Excel对象  
  141.         if (EXCEL_2003_ContentType.equals(contentType)){  
  142.             wb =(Workbook) new HSSFWorkbook(stream);    //2003  
  143.         }else if(EXCEL_2007_ContentType.equals(contentType)) {  
  144.             wb =(Workbook) new XSSFWorkbook(stream);    //2007  
  145.         }  
  146.         int rowSize = 0;  
  147.         Cell cell = null;  
  148.   
  149.         Sheet st = wb.getSheetAt(sheetIndex);  
  150.         for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {  
  151.             Row row = st.getRow(rowIndex);  
  152.             if (null == row) {  
  153.                 continue;  
  154.             }  
  155. //          int tempRowSize = row.getLastCellNum() + 1;  
  156.             int tempRowSize = row.getPhysicalNumberOfCells();  
  157.               
  158.             if(colCnt==null){  
  159.                 if (tempRowSize > rowSize) {  
  160.                     rowSize = tempRowSize;  
  161.                 }  
  162.                 colCnt=rowSize;  
  163.             }  
  164.             String[] values = new String[colCnt];  
  165.             Arrays.fill(values, ”“);  
  166.             boolean hasValue = false;  
  167.             for (short columnIndex = 0; columnIndex < colCnt; columnIndex++) {  
  168.                 String value = “”;  
  169.                 cell = row.getCell(columnIndex);  
  170.                 if (null != cell) {  
  171.                     switch (cell.getCellType()) {  
  172.                     case HSSFCell.CELL_TYPE_STRING:  
  173.                         value = cell.getStringCellValue();  
  174.                         break;  
  175.                     case HSSFCell.CELL_TYPE_NUMERIC:  
  176.                         if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  177.                             Date date = cell.getDateCellValue();  
  178.                             if (null != date) {  
  179.                                 value = new SimpleDateFormat(“yyyy-MM-dd”).format(date);  
  180.                             } else {  
  181.                                 value = “”;  
  182.                             }  
  183.                         } else {  
  184.                             DecimalFormat df = new DecimalFormat(“0.#######”);                                      
  185.                             //value = df.format(cell.getNumericCellValue());                                  
  186.                             value = String.valueOf(df.format(cell.getNumericCellValue()));  
  187.                         }  
  188.                         break;  
  189.                     case HSSFCell.CELL_TYPE_FORMULA:  
  190.                         // 公式生成的数据  
  191.                         if (!”“.equals(cell.getStringCellValue())) {  
  192.                             value = cell.getStringCellValue();  
  193.                         } else {  
  194.                             value = cell.getNumericCellValue() + ”“;  
  195.                         }  
  196.                         break;  
  197.                     case HSSFCell.CELL_TYPE_BLANK:  
  198.                         break;  
  199.                     case HSSFCell.CELL_TYPE_ERROR:  
  200.                         value = “”;  
  201.                         break;  
  202.                     case HSSFCell.CELL_TYPE_BOOLEAN:  
  203.                         value = (cell.getBooleanCellValue() == true ? “Y” : “N”);  
  204.                         break;  
  205.                     default:  
  206.                         value = “”;  
  207.                     }  
  208.                 }  
  209.                 if (columnIndex == 0 && value.trim().equals(“”)) {  
  210.                     break;  
  211.                 }  
  212.                 values[columnIndex] = rightTrim(value);  
  213.                 hasValue = true;  
  214.                 }  
  215.             if (hasValue) {  
  216.                 result.add(values);  
  217.             }  
  218.         }  
  219.               
  220.         stream.close();  
  221.         String[][] returnArray = new String[result.size()][colCnt];  
  222.         for (int i = 0; i < returnArray.length; i++) {  
  223.             returnArray[i] = (String[]) result.get(i);  
  224.         }  
  225.         return returnArray;  
  226.     }  
  227.       
  228.     /**  
  229.      * 去除字符串右侧空格(直接使用trim()将不能支持中间存在空格的单元格)  
  230.      * @param str  
  231.      * @return  
  232.      */  
  233.     public static String rightTrim(String str) {  
  234.         if (str == null) {  
  235.             return ”“;  
  236.         }  
  237.         int length = str.length();  
  238.         for (int i = length - 1; i >= 0; i–) {  
  239.             if (0x20 != str.charAt(i)) {  
  240.                 break;  
  241.             }  
  242.             length–;  
  243.         }  
  244.         return str.substring(0, length);  
  245.     }  
  246. }  
package org.nercita.bcp.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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 org.springframework.web.multipart.MultipartFile;

/**
 * excel文件导入工具类
 */
public class ImportUtil {

    public static String EXCEL_2007_ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    public static String EXCEL_2003_ContentType = "application/vnd.ms-excel";

    /**
     * excel文件导入
     * @param file
     * @param ignoreRows 需要忽略掉的行数
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String[][] importFile(MultipartFile file, int ignoreRows) throws FileNotFoundException, IOException {
        List<String[]> result = new ArrayList<String[]>();
        String contentType = file.getContentType();  //内容类型 
        InputStream stream = file.getInputStream();  //输入流
        Workbook wb=null;
        //根据inputStream建立一个Excel对象
        if (EXCEL_2003_ContentType.equals(contentType)){
            wb =(Workbook) new HSSFWorkbook(stream);    //2003
        }else if(EXCEL_2007_ContentType.equals(contentType)) {
            wb =(Workbook) new XSSFWorkbook(stream);    //2007
        }
        int rowSize = 0;
        Cell cell = null;
        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            Sheet st = wb.getSheetAt(sheetIndex);
            for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
                Row row = st.getRow(rowIndex);
                if (null == row) {
                    continue;
                }
                int tempRowSize = row.getLastCellNum() + 1;
                if (tempRowSize > rowSize) {
                    rowSize = tempRowSize;
                }
                String[] values = new String[rowSize];
                Arrays.fill(values, "");
                boolean hasValue = false;
                for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
                    String value = "";
                    cell = row.getCell(columnIndex);
                    if (null != cell) {
                        switch (cell.getCellType()) {
                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getStringCellValue();
                            break;
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                Date date = cell.getDateCellValue();
                                if (null != date) {
                                    value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                                } else {
                                    value = "";
                                }
                            } else {
                                DecimalFormat df = new DecimalFormat("0.#######");                                    
                                //value = df.format(cell.getNumericCellValue());                                
                                value = String.valueOf(df.format(cell.getNumericCellValue()));
                            }
                            break;
                        case HSSFCell.CELL_TYPE_FORMULA:
                            // 公式生成的数据
                            if (!"".equals(cell.getStringCellValue())) {
                                value = cell.getStringCellValue();
                            } else {
                                value = cell.getNumericCellValue() + "";
                            }
                            break;
                        case HSSFCell.CELL_TYPE_BLANK:
                            break;
                        case HSSFCell.CELL_TYPE_ERROR:
                            value = "";
                            break;
                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            value = (cell.getBooleanCellValue() == true ? "Y" : "N");
                            break;
                        default:
                            value = "";
                        }
                    }
                    if (columnIndex == 0 && value.trim().equals("")) {
                        break;
                    }
                    values[columnIndex] = rightTrim(value);
                    hasValue = true;
                    }
                if (hasValue) {
                    result.add(values);
                }
            }
        }
        stream.close();
        String[][] returnArray = new String[result.size()][rowSize];
        for (int i = 0; i < returnArray.length; i++) {
            returnArray[i] = (String[]) result.get(i);
        }
        return returnArray;
    }

    /**
     * excel文件导入
     * @param file
     * @param ignoreRows 需要忽略掉的行数
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String[][] importFile(MultipartFile file,int sheetIndex, int ignoreRows,Integer colCnt) throws FileNotFoundException, IOException {
        List<String[]> result = new ArrayList<String[]>();
        String contentType = file.getContentType();  //内容类型 
        InputStream stream = file.getInputStream();  //输入流
        Workbook wb=null;
        //根据inputStream建立一个Excel对象
        if (EXCEL_2003_ContentType.equals(contentType)){
            wb =(Workbook) new HSSFWorkbook(stream);    //2003
        }else if(EXCEL_2007_ContentType.equals(contentType)) {
            wb =(Workbook) new XSSFWorkbook(stream);    //2007
        }
        int rowSize = 0;
        Cell cell = null;

        Sheet st = wb.getSheetAt(sheetIndex);
        for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
            Row row = st.getRow(rowIndex);
            if (null == row) {
                continue;
            }
//          int tempRowSize = row.getLastCellNum() + 1;
            int tempRowSize = row.getPhysicalNumberOfCells();

            if(colCnt==null){
                if (tempRowSize > rowSize) {
                    rowSize = tempRowSize;
                }
                colCnt=rowSize;
            }
            String[] values = new String[colCnt];
            Arrays.fill(values, "");
            boolean hasValue = false;
            for (short columnIndex = 0; columnIndex < colCnt; columnIndex++) {
                String value = "";
                cell = row.getCell(columnIndex);
                if (null != cell) {
                    switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_STRING:
                        value = cell.getStringCellValue();
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            Date date = cell.getDateCellValue();
                            if (null != date) {
                                value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                            } else {
                                value = "";
                            }
                        } else {
                            DecimalFormat df = new DecimalFormat("0.#######");                                    
                            //value = df.format(cell.getNumericCellValue());                                
                            value = String.valueOf(df.format(cell.getNumericCellValue()));
                        }
                        break;
                    case HSSFCell.CELL_TYPE_FORMULA:
                        // 公式生成的数据
                        if (!"".equals(cell.getStringCellValue())) {
                            value = cell.getStringCellValue();
                        } else {
                            value = cell.getNumericCellValue() + "";
                        }
                        break;
                    case HSSFCell.CELL_TYPE_BLANK:
                        break;
                    case HSSFCell.CELL_TYPE_ERROR:
                        value = "";
                        break;
                    case HSSFCell.CELL_TYPE_BOOLEAN:
                        value = (cell.getBooleanCellValue() == true ? "Y" : "N");
                        break;
                    default:
                        value = "";
                    }
                }
                if (columnIndex == 0 && value.trim().equals("")) {
                    break;
                }
                values[columnIndex] = rightTrim(value);
                hasValue = true;
                }
            if (hasValue) {
                result.add(values);
            }
        }

        stream.close();
        String[][] returnArray = new String[result.size()][colCnt];
        for (int i = 0; i < returnArray.length; i++) {
            returnArray[i] = (String[]) result.get(i);
        }
        return returnArray;
    }

    /**
     * 去除字符串右侧空格(直接使用trim()将不能支持中间存在空格的单元格)
     * @param str
     * @return
     */
    public static String rightTrim(String str) {
        if (str == null) {
            return "";
        }
        int length = str.length();
        for (int i = length - 1; i >= 0; i--) {
            if (0x20 != str.charAt(i)) {
                break;
            }
            length--;
        }
        return str.substring(0, length);
    }
}


 

猜你喜欢

转载自blog.csdn.net/hc_ttxs/article/details/79262459