Spring POIによるExcelインポートエクスポート


Apache POIは、Office Open XML(OOXML)規格とマイクロソフトのOLE 2複合ドキュメントフォーマット(OLE 2)に適合する様々なJava APIの作成とメンテナンス操作である.Javaを使用してMS Excelファイルを読み込み、作成します.また、Javaを使用してMS WordファイルとMSPowerPointファイルを読み込み、作成することもできます.Apache POIは、JavaオペレーションExcelソリューション(Excel 97-2008に適用)を提供します.
       簡単に理解すると、POIを通じてjavaはofficeと連絡を取ることができます.
       今回のプロジェクトの実践はSSMフレームワークに基づいて、簡単にExcel一括導入導出機能をカプセル化し、実現過程は以下の通りである.
       1.maven javaパッケージのインポート:
   
	org.apache.poi  
	poi-ooxml  
	3.5-FINAL  
   

       2.Excelエンティティの作成--ExcelBean
/**
 * 
* @Description:     excel
* @author haipeng
* @date 2017 4 11 
 */
public class ExcelBean implements java.io.Serializable {
	 private String headTextName;//  (  ) 
     private String propertyName;//     
     private Integer cols;//      
     private XSSFCellStyle cellStyle;
     
     public ExcelBean(){
    	 
     }
     public ExcelBean(String headTextName, String propertyName){
    	 this.headTextName = headTextName;
         this.propertyName = propertyName;
     }
     
     public ExcelBean(String headTextName, String propertyName, Integer cols) {
         super();
         this.headTextName = headTextName;
         this.propertyName = propertyName;
         this.cols = cols;
     } 
     
     public String getHeadTextName() {
		return headTextName;
	}

	public void setHeadTextName(String headTextName) {
		this.headTextName = headTextName;
	}

	public String getPropertyName() {
		return propertyName;
	}

	public void setPropertyName(String propertyName) {
		this.propertyName = propertyName;
	}

	public Integer getCols() {
		return cols;
	}

	public void setCols(Integer cols) {
		this.cols = cols;
	}

	public XSSFCellStyle getCellStyle() {
		return cellStyle;
	}

	public void setCellStyle(XSSFCellStyle cellStyle) {
		this.cellStyle = cellStyle;
	}
}

      3.  Excelツールクラスのカプセル化--ExcelUtils
public class ExcelUtils {
	private final static String excel2003L =".xls";    //2003-    excel  
    private final static String excel2007U =".xlsx";   //2007+    excel  
    /*************************************    ****************************/
    public static  List> getBankListByExcel(InputStream in,String fileName) throws Exception{  
        List> list = null;  
          
        //  Excel     
        Workbook work = getWorkbook(in,fileName);  
        if(null == work){  
            throw new Exception("  Excel     !");  
        }  
        Sheet sheet = null;  
        Row row = null;  
        Cell cell = null;  
          
        list = new ArrayList>();  
        //  Excel    sheet  
        for (int i = 0; i < work.getNumberOfSheets(); i++) {  
            sheet = work.getSheetAt(i);  
            if(sheet==null){continue;}  
              
            //    sheet       
            for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {  
                row = sheet.getRow(j);  
                if(row==null||row.getFirstCellNum()==j){continue;}  
                  
                //        
                List li = new ArrayList();  
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {  
                    cell = row.getCell(y);  
                    li.add(getCellValue(cell));  
                }  
                list.add(li);  
            }  
        }  
//        work.close();  
        return list;  
    }  
      
    /** 
     *   :      ,            
     * @param inStr,fileName 
     * @return 
     * @throws Exception 
     */  
    public static  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{  
        Workbook wb = null;  
        String fileType = fileName.substring(fileName.lastIndexOf("."));  
        if(excel2003L.equals(fileType)){  
            wb = new HSSFWorkbook(inStr);  //2003-  
        }else if(excel2007U.equals(fileType)){  
            wb = new XSSFWorkbook(inStr);  //2007+  
        }else{  
            throw new Exception("         !");  
        }  
        return wb;  
    }  
  
    /** 
     *   :            
     * @param cell 
     * @return 
     */  
    public static  Object getCellValue(Cell cell){  
        Object value = null;  
        DecimalFormat df = new DecimalFormat("0");  //   number String    
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //       
        DecimalFormat df2 = new DecimalFormat("0.00");  //       
          
        switch (cell.getCellType()) {  
        case Cell.CELL_TYPE_STRING:  
            value = cell.getRichStringCellValue().getString();  
            break;  
        case Cell.CELL_TYPE_NUMERIC:  
            if("General".equals(cell.getCellStyle().getDataFormatString())){  
                value = df.format(cell.getNumericCellValue());  
            }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){  
                value = sdf.format(cell.getDateCellValue());  
            }else{  
                value = df2.format(cell.getNumericCellValue());  
            }  
            break;  
        case Cell.CELL_TYPE_BOOLEAN:  
            value = cell.getBooleanCellValue();  
            break;  
        case Cell.CELL_TYPE_BLANK:  
            value = "";  
            break;  
        default:  
            break;  
        }  
        return value;  
    }  
    /****************************************    ***************************************
	/**
	     *      EXCEL
	     * 
	     * @param sheetName      
	     * @param clazz     model  
	     * @param objs   excel       model   
	     * @param map         cell    
	     * @return
	     * @throws IllegalArgumentException
	     * @throws IllegalAccessException
	     * @throws InvocationTargetException
	     * @throws ClassNotFoundException
	     * @throws IntrospectionException
	     * @throws ParseException
	     */
	public static XSSFWorkbook createExcelFile(Class clazz, List objs,Map> map,String sheetName) throws IllegalArgumentException,IllegalAccessException,
	InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException{
	        //     Excel    
	        XSSFWorkbook workbook = new XSSFWorkbook();
	        //  Excel         ,      ,      Sheet  
	        XSSFSheet sheet = workbook.createSheet(sheetName);
	        //    excel       excel         ,       ;
	        createFont(workbook);//    
	        createTableHeader(sheet, map);//    ( )
	        createTableRows(sheet, map, objs, clazz);//    
	        return workbook;
	    }
	private static XSSFCellStyle fontStyle;
	private static XSSFCellStyle fontStyle2;
	public static void createFont(XSSFWorkbook workbook) {
        //   
		fontStyle = workbook.createCellStyle();
        XSSFFont font1 = workbook.createFont();
        font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        font1.setFontName("  ");
        font1.setFontHeightInPoints((short) 14);//       
        fontStyle.setFont(font1);
        fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); //    
        fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);//    
        fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);//    
        fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);//    
        fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); //   

        //   
        fontStyle2=workbook.createCellStyle();
		XSSFFont font2 = workbook.createFont();
		font2.setFontName("  ");
		font2.setFontHeightInPoints((short) 10);//       
		fontStyle2.setFont(font2);     
		fontStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN); //    
        fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);//    
        fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);//    
        fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);//    
        fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); //   
	}
	
	/**
     *   ExcelMapping     (    )
     * 
     * @param sheet
     *               
     * @param map
     *                          
     */
    public static final void createTableHeader(XSSFSheet sheet, Map> map) {
        int startIndex=0;//cell    
        int endIndex=0;//cell    

        for (Map.Entry> entry : map.entrySet()) {
            XSSFRow row = sheet.createRow(entry.getKey());
            List excels = entry.getValue();
            for (int x = 0; x < excels.size(); x++) {
                //     
                if(excels.get(x).getCols()>1){
                    if(x==0){                                     
                    	endIndex+=excels.get(x).getCols()-1;
                        CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
                        sheet.addMergedRegion(range);
                        startIndex+=excels.get(x).getCols();
                    }else{
                        endIndex+=excels.get(x).getCols();
                        CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
                        sheet.addMergedRegion(range);
                        startIndex+=excels.get(x).getCols();
                    }
                    XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());
                    cell.setCellValue(excels.get(x).getHeadTextName());//     
                    if (excels.get(x).getCellStyle() != null) {
                        cell.setCellStyle(excels.get(x).getCellStyle());//     
                    }
                    cell.setCellStyle(fontStyle);
                }else{

                    XSSFCell cell = row.createCell(x);
                    cell.setCellValue(excels.get(x).getHeadTextName());//     
                    if (excels.get(x).getCellStyle() != null) {
                        cell.setCellStyle(excels.get(x).getCellStyle());//     
                    }
                    cell.setCellStyle(fontStyle);
                }

            }
        }
    }
	
	/**
     * 
     * @param sheet
     * @param map
     * @param objs
     * @param clazz
     */
    @SuppressWarnings("rawtypes")
    public static void createTableRows(XSSFSheet sheet, Map> map, List objs, Class clazz)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException,
            ClassNotFoundException, ParseException {

        int rowindex = map.size();
        int maxKey = 0;
        List ems = new ArrayList<>();
        for (Map.Entry> entry : map.entrySet()) {
            if (entry.getKey() > maxKey) {
                maxKey = entry.getKey();
            }
        }
        ems = map.get(maxKey);

        List widths = new ArrayList(ems.size());
        for (Object obj : objs) {
            XSSFRow row = sheet.createRow(rowindex);
            for (int i = 0; i < ems.size(); i++) {
                ExcelBean em = (ExcelBean) ems.get(i);
            //   get   
                PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object rtn = getMethod.invoke(obj);
                String value = "";
                //              
                if (rtn != null) {
                    if (rtn instanceof Date) {
                        value = DateUtils.date2String((Date) rtn,"yyyy-MM-dd");
                    } else if(rtn instanceof BigDecimal){
                    	NumberFormat nf = new DecimalFormat("#,##0.00");
                    	value=nf.format((BigDecimal)rtn).toString();
                    } else if((rtn instanceof Integer) && (Integer.valueOf(rtn.toString())<0 )){
                    	value="--";
                    }else {
                        value = rtn.toString();
                    }
                }
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(value);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                cell.setCellStyle(fontStyle2);
                //       
                int width = value.getBytes().length * 300;
                //     ,    
                if (widths.size() <= i) {
                    widths.add(width);
                    continue;
                }
                //     ,    
                if (width > widths.get(i)) {
                    widths.set(i, width);
                }
            }
            rowindex++;
        }
        //     
        for (int index = 0; index < widths.size(); index++) {
            Integer width = widths.get(index);
            width = width < 2500 ? 2500 : width + 300;
            width = width > 10000 ? 10000 + 300 : width + 300;
            sheet.setColumnWidth(index, width);
        }
    }
}

      4.  HTMLページに必要なjsをインポート

      5.  HTMLにテストコントロールを

      6.aラベルによるgetリクエストのエクスポートは であり、インポートはajaxのpostリクエストによって される.
$('#upLoadPayerCreditInfoExcel').click(function(){
	var cacheVersion=$("#cacheVersion").val();
    if(checkData()){  
        $('#uploadForm').ajaxSubmit({    
            url:$("#root").val()+'/creditInfo/uploadReceiverCreditInfoExcel.html',
            data:{'cacheVersion':cacheVersion},
            dataType: 'text'
        });   
    }  
});  

//JS  form      
function checkData(){  
   var fileDir = $("#upfile").val();  
   var suffix = fileDir.substr(fileDir.lastIndexOf("."));  
   if("" == fileDir){  
       alert("       Excel  !");  
       return false;  
   }  
   if(".xls" != suffix && ".xlsx" != suffix ){  
       alert("  Excel       !");  
       return false;  
   }  
   return true;  
}

       7.コントロールエンド
       エクスポート:
@RequestMapping(value = "/downLoadPayerCreditInfoExcel", method = RequestMethod.GET)
	@ResponseBody
    public void downLoadPayerCreditInfoExcel(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		response.reset();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
        String dateStr = sdf.format(new Date());
        Long companyId=UserUtils.getCompanyIdBySession(session);
        Map map=new HashMap();
        //         
        response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xlsx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        XSSFWorkbook workbook=null;
		try {
			//  Excel  
			workbook = creditInfoService.exportPayerCreditInfoExcel(companyId);
		} catch (IllegalArgumentException | IllegalAccessException
				| InvocationTargetException | ClassNotFoundException
				| IntrospectionException | ParseException e1) {
			e1.printStackTrace();
		}
        OutputStream output;
		try {
			output = response.getOutputStream();
		
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            bufferedOutPut.flush();
            workbook.write(bufferedOutPut);
            bufferedOutPut.close();
            
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

       インポート:
@ResponseBody  
    @RequestMapping(value="uploadPayerCreditInfoExcel",method={RequestMethod.GET,RequestMethod.POST})  
    Public void uploadPayerCreditInfoExcel(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception {  
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
        MultipartFile file = multipartRequest.getFile("upfile");  
        if(file.isEmpty()){  
            throw new Exception("     !");  
        }  
        Long companyId=UserUtils.getCompanyIdBySession(session);
        Long userId=UserUtils.getUserIdBySession(session);
        InputStream in = file.getInputStream();
        creditInfoService.uploadPayerCreditInfoExcel(in,file,companyId,userId);
        in.close();
        PrintWriter out = null;  
        response.setCharacterEncoding("utf-8");  //  ajax            
        out = response.getWriter();  
        out.print("      !");  
        out.flush();  
        out.close();  
    }

       8、サービス
 
          インポートし、excelから したデータをList>に し、エンティティを して を います.
public void uploadPayerCreditInfoExcel(InputStream in, MultipartFile file,Long companyId,Long userId) throws Exception {
	List> listob = ExcelUtils.getBankListByExcel(in,file.getOriginalFilename());  
	List creditInfoList=new ArrayList();
	for (int i = 0; i < listob.size(); i++) {  
            List ob = listob.get(i);  
            CreditInfoBean creditInfoBean = new CreditInfoBean();
            creditInfoBean.setCompanyName(String.valueOf(ob.get(0)));
            creditInfoBean.setBillType(String.valueOf(ob.get(1)));
            creditInfoBean.setBillNumber(String.valueOf(ob.get(2)));
            BigDecimal bd=new BigDecimal(String.valueOf(ob.get(3)));   
            creditInfoBean.setBuyerBillAmount(bd.setScale(2, BigDecimal.ROUND_HALF_UP));
            creditInfoBean.setReceiveTime(String.valueOf(ob.get(4)));
            creditInfoBean.setBuyerRemark(String.valueOf(ob.get(5)));
            creditInfoList.add(creditInfoBean);
        }  
}

         エクスポート:
public XSSFWorkbook exportPayerCreditInfoExcel(Long companyId) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, IntrospectionException, com.sun.tools.example.debug.expr.ParseException {
		List creditInfoList=creditInfoDao.listAllPayerCreditInfoPage(companyId);
		List ems=new ArrayList<>();
		Map>map=new LinkedHashMap<>();
		XSSFWorkbook book=null;
		ems.add(new ExcelBean("     ","companyName",0));
		ems.add(new ExcelBean("    ","billType",0));
		ems.add(new ExcelBean("   ","billNumber",0));
//		ems.add(new ExcelBean("      ","isBuyerIquidation",0));
		ems.add(new ExcelBean("    ","buyerBillAmount",0));
		ems.add(new ExcelBean("    ","buyerPayTime",0));
		ems.add(new ExcelBean("    ","overplusDays",0));
		ems.add(new ExcelBean("  ","buyerBillStatus",0));
		map.put(0, ems);
		List afterChangeList=changeBuyerStatus(creditInfoList);
		book=ExcelUtils.createExcelFile(CreditInfoBean.class, afterChangeList, map, "      ");
		return book;
}