这段コード提神-JavaはEXCELテンプレート化導出を実現します.ajax+springMVCまたはStrutsは例です.


いつもあれだけのことがあって、振り返るに忍びないです.
仕事をする時はこの点で基本的にコードを持ってきて元気を出さなければなりません.
第一歩:EXCELテンプレートを用意する
         /***
	 *   excel  Sheet     
	 */
	public Workbook doExportExcelSheet(Workbook workbook, String title, String[] headers, Collection<T> dataset, String pattern, int cellnums, boolean isIndex){
		//      ,sheet
		Sheet sheet = workbook.createSheet(title);
		//         16   
		sheet.setDefaultColumnWidth(16);
		
		////       -     
		CellStyle styleForTitle = workbook.createCellStyle();
		//      
		styleForTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //    
		styleForTitle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //   
		styleForTitle.setBorderLeft(HSSFCellStyle.BORDER_THIN); //   
		styleForTitle.setBorderTop(HSSFCellStyle.BORDER_THIN); //   
		styleForTitle.setBorderRight(HSSFCellStyle.BORDER_THIN); //   
		//  
		Font fontForTitle = workbook.createFont();
		fontForTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //  
		fontForTitle.setFontHeightInPoints((short)10); //  
		fontForTitle.setFontName("  "); //  
		styleForTitle.setFont(fontForTitle);
		
		////       -      -    
		CellStyle styleForStr = workbook.createCellStyle();
		//      
		styleForStr.setAlignment(HSSFCellStyle.ALIGN_CENTER); //    
		styleForStr.setBorderBottom(HSSFCellStyle.BORDER_THIN); //   
		styleForStr.setBorderLeft(HSSFCellStyle.BORDER_THIN); //   
		styleForStr.setBorderTop(HSSFCellStyle.BORDER_THIN); //   
		styleForStr.setBorderRight(HSSFCellStyle.BORDER_THIN); //   
		//  
		Font fontForStr = workbook.createFont();
		fontForStr.setFontHeightInPoints((short)10); //  
		fontForStr.setFontName("  "); //  
		styleForStr.setFont(fontForStr);
		
		////       -      -   
		CellStyle styleForNum = workbook.createCellStyle();
		//      
		styleForNum.setAlignment(HSSFCellStyle.ALIGN_RIGHT); //   
		styleForNum.setBorderBottom(HSSFCellStyle.BORDER_THIN); //   
		styleForNum.setBorderLeft(HSSFCellStyle.BORDER_THIN); //   
		styleForNum.setBorderTop(HSSFCellStyle.BORDER_THIN); //   
		styleForNum.setBorderRight(HSSFCellStyle.BORDER_THIN); //   
//		styleForNum.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); //          ,        (  4 ,  2 )
		//  
		Font fontForNum = workbook.createFont();
		fontForNum.setFontHeightInPoints((short)10); //  
		fontForNum.setFontName("  "); //  
		styleForNum.setFont(fontForNum);
		
		//      
		Row row = sheet.createRow(0);
		for(short i = 0; i < headers.length; i++){
			Cell cell = row.createCell(i);
			cell.setCellStyle(styleForTitle); //    
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}
		
		
		//      ,     
		Iterator<T> it = dataset.iterator();
		int index = 0;
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			T t = (T) it.next();
			//     ,  javabean       ,    getXxx()       
			Field[] fields = t.getClass().getDeclaredFields();
			for (short i = 0; i < fields.length - cellnums; i++) {
				Cell cell = row.createCell(i);
				//     
				if (isIndex) {
					if (i == (short)0) {
						cell.setCellValue(index);
					}
				}
				Field field = fields[i];
				String fieldName = field.getName();
				if (!"id".equals(fieldName)) {
					String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
					try {
						Class tCls = t.getClass();
						Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
						Object value = getMethod.invoke(t, new Object[] {});
						//                
						String textValue = null;
						if (value instanceof Integer) {
							int intValue = (Integer) value;
							cell.setCellValue(intValue);
							cell.setCellStyle(styleForNum); //    
						} else if (value instanceof Short) {
							cell.setCellValue((Short) value);
							cell.setCellStyle(styleForNum); //    
						} else if (value instanceof Float) {
							float fValue = (Float) value;
							cell.setCellValue(fValue);
							cell.setCellStyle(styleForNum); //    
						} else if (value instanceof Double) {
							double dValue = (Double) value;
							cell.setCellValue(dValue);
							cell.setCellStyle(styleForNum); //    
						} else if (value instanceof BigDecimal) {
							BigDecimal dValue = (BigDecimal) value;
							cell.setCellValue(dValue.floatValue());
							cell.setCellStyle(styleForNum); //    
						} else if (value instanceof Long) {
							long longValue = (Long) value;
							cell.setCellValue(longValue);
							cell.setCellStyle(styleForNum); //    
						} else if (value instanceof Date) {
							Date date = (Date) value;
							SimpleDateFormat sdf = new SimpleDateFormat(pattern);
							textValue = sdf.format(date);
							cell.setCellValue(textValue);
							cell.setCellStyle(styleForStr); //    
						} else {
							//                 
							Object obj_value = (value == null) ? "" : value;
							textValue = obj_value.toString();
							cell.setCellValue(textValue);
							cell.setCellStyle(styleForStr); //    
						}
					} catch (SecurityException e) {
                        e.printStackTrace();
						log.error(e.getStackTrace()[0].toString());
					} catch (NoSuchMethodException e) {
                        e.printStackTrace();
						log.error(e.getStackTrace()[0].toString());
					} catch (IllegalArgumentException e) {
                        e.printStackTrace();
						log.error(e.getStackTrace()[0].toString());
					} catch (IllegalAccessException e) {
                        e.printStackTrace();
						log.error(e.getStackTrace()[0].toString());
					} catch (InvocationTargetException e) {
                        e.printStackTrace();
						log.error(e.getStackTrace()[0].toString());
					} finally {
						//     
					}
				}
			}
		}
		it = null;
		return workbook;
	}
第二部:呼び出し--ajax+sprigMVCのsprigMVCインターフェース部分
    @FunctionCode(value = "user.exportUserInfoList", descript = "      ")
    @Override
    public ApiResponse<String> exportUserInfoList(ApiRequest apiRequest) throws ParseException {
		List<UserInfoExportBean> exportList=getUserInfoExportBeanList();//     ,    
        
        Workbook writeWB = new SXSSFWorkbook(500);
        String exName = "WXZtongji" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
        if (!exportList.isEmpty()) {
            String[] colName = {"    ", "    ", "  ", "    ", "    ","    "};
            ExportExcelUtil export = new ExportExcelUtil();
           //  excel  
            writeWB = export.doExportExcelSheet(writeWB, "  ", colName, exportList, "yyyy-MM-dd", 0, false);
        }
        String filePath =writeFile(writeWB,exName);//    
        return new ApiResponse<String>(RestResultEnum.SUCCESS, 1, filePath);//      
    }
    private List<UserInfoExportBean> getUserInfoExportBeanList() {
    	List<UserInfoExportBean> exportList = new ArrayList<UserInfoExportBean>();
        List<UserInfoPo> userInfos = this.userInfoMapper.userInfoListStatistics();
        if(!userInfos.isEmpty()){
            for(UserInfoPo po :userInfos){
                <span style="color:#ff6600;">//"    ", "    ", "  ", "    ", "    ","    "          </span>
                UserInfoExportBean bean =new UserInfoExportBean();
                bean.setUserShopName(po.getUserShopName());
                bean.setTelphone(po.getTelphone());
                bean.setAddress(po.getAddress());
                bean.setBdUserName(po.getBdUserName());
                bean.setCreateTime(po.getCreateTime());
                bean.setVantages(po.getVantages());
                exportList.add(bean);
            }
        }
		return exportList;
	}

	private String writeFile(Workbook writeWB,String exName) {
        String filePath ="";
        try {
            //      
            //  String fileFolder = "D://";//    
            String fileFolder = "/test/test";//      
            //        
            File f = new File(fileFolder);
            if (!f.exists()) {
                //     ??
                f.mkdirs();
            }
            //    
            FileOutputStream fos = new FileOutputStream(fileFolder + "/" + exName);
            writeWB.write(fos);
            fos.close();
            //     
            filePath = fileServer + "/" + exName;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
第三部分:ajaxフロントエンド呼び出し(node.jsのコードの一部は、表ではない)
ドル("刋export Btn").click(function(ev){        return$ajax({          url:'/url'          type:'post'は、          dataType:'json'は、          data:{            start:$(「璖begiDate」).val()            end:$(「璖endDate」).val()          },           success:function(d){            if(d.success){              location.href=d.address;            }           }         });       });