POI 작업 excel 예제 도구 클래스

최근 프로젝트는 excel을 사용하여 페이지의 폼 데이터를 저장해야 하기 때문에poi조작excel에 대해 알아보고 다음과 같이 썼지만 전반적으로 좋지 않다고 생각했다
특히: 여기 를 발표하여 여러분 에게 평론 을 드리고, 넓은 뜻 을 모아 생각하며, 많은 지도 를 바랍니다
   1. 워크북 처리 클래스
/**
 * Excel WorkBook 
 * @author dsy
 * @version 1.0
 */
public class ExcelWorkBook {
	
	public HSSFWorkbook workbook = null;
	public static HSSFWorkbook workbookTemp = null;
	// workbookName
	private String workbookName = null;
	private HSSFSheet sheet = null;
	private FileOutputStream fileOut;
	
	public ExcelWorkBook() {
		if(workbook != null) {
			workbook = null;
		}
		workbook = workbookTemp;
	}
	
	public ExcelWorkBook(String workbookName) {
		workbook = workbookTemp;
		setWorkbookName(workbookName);
	}
	public String getWorkbookName() {
		return workbookName;
	}

	public void setWorkbookName(String workbookName) {
		workbookName = workbookName;
	}

	public HSSFSheet getSheet() {
		sheet = workbook.createSheet(getWorkbookName());
		return sheet;
	}
	
	/**
	 *  stylUtils workbook 
	 * @return
	 */
	public static HSSFWorkbook getWorkbook() {
		return workbookTemp;
	}

	public static void setWorkbook(HSSFWorkbook workbook) {
		workbookTemp = workbook;
	}
	
	/**
	 *  WorkBook 
	 * @param excelName
	 */
	public void writerFileStream(String excelName) {
		try {
			fileOut = new FileOutputStream(excelName);
			workbook.write(fileOut);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				fileOut.flush();
				fileOut.close();
				if(workbook != null) {
					workbook = null;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}

  
   2. Excel Row 도구 클래스
 
/**
 * Excel Row 
 * @author dsy
 * @version 1.0
 */
public class ExcelSheetRow {
	
	
	public ExcelSheetRow() {
		// TODO Auto-generated constructor stub
	}

	public static HSSFSheet sheet = null;
	/**
	 *  Sheet 
	 */
	private static String sheetName = null;
	private static HSSFRow row = null;
	
	
	/**
	 *  
	 * @param sheet
	 * @return
	 */
	public static HSSFRow createCurrSheetTitle(ExcelWorkBook work) {
	   HSSFSheet sheet = work.getSheet();
	   row = sheet.createRow(0);
	   return row;
	}
	
	/**
	 *  excel 
	 * @param sheet
	 * @param i
	 * @return
	 */
	public static HSSFRow createCurrSheetRecord(ExcelWorkBook work,int i) {
		HSSFSheet sheet = work.getSheet();
		row = sheet.createRow(i+1);
		return row;
	} 

	public static String getSheetName() {
		return sheetName;
	}

	public static void setSheetName(String sheetName) {
		ExcelSheetRow.sheetName = sheetName;
	}

}

  
   3.Excel Cell 도구 클래스
/**
 * Excel Cell 
 * @author dsy
 * @version 1.0
 */
public class ExcelSheetCell {
	
	private static HSSFRow row = null;
	private static HSSFCell cell = null;
	
	
	
	/**
	 *  excel 
	 * @param sheet [ ]
	 * @param firstRowValue [ ]
	 * @param style [ ]
	 */
	public static void createCurrRowTitle(ExcelSheetRow sheetRow,ExcelWorkBook work ,String[] firstRowValue,HSSFCellStyle style) {
		row = sheetRow.createCurrSheetTitle(work);
		for (int i = 0; i < firstRowValue.length; i++) {
			cell = row.createCell((short) i);
			cell.setCellStyle(style);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(firstRowValue[i]);
		}
	}
	
	/**
	 *  excel , 
	 * @param sheet [ ]
	 * @param beanList [ ,i=Object[]]
	 * @param style [ ]
	 */
	public static void createCurrRowRecord(ExcelSheetRow sheetRow,ExcelWorkBook work,List beanList,HSSFCellStyle style) {
		Object[] obj = null;
		for (int i = 0; i < beanList.size(); i++) {
			row = sheetRow.createCurrSheetRecord(work,i);
			obj = (Object[]) beanList.get(i);
			if (obj != null) {
				createExcelCell(row, obj,style);
			}
		}
	}
	
	/**
	 *  
	 *  , 
	 */
	private static void createExcelCell(HSSFRow row, Object[] obj,HSSFCellStyle style) {
		try {
			for (int i = 0; i < obj.length; i++) {
				try {
					if (obj[i].toString() != null) {

						cell = row.createCell((short) i);
						cell.setCellStyle(style);
						cell.setEncoding(HSSFCell.ENCODING_UTF_16);
						cell.setCellValue(obj[i].toString());
					}
				} catch (NullPointerException e) {
					continue;
				}

			}
		} catch (Exception ex) {
			System.out.print(ex);
		}
	}
}

 
   4. Excel 스타일 도구 모음
/**
 * Excel Style 
 * @author dsy
 * @version 1.0
 */
public class ExcelCellStyleUtils{

	// 
	public static HSSFCellStyle titleStyle;
	// 
	public static HSSFCellStyle dataStyle;
	// 
	public static HSSFCellStyle nameStyle;
	// 
	public static HSSFCellStyle linkStyle;
	public static HSSFFont font;
	
	public ExcelCellStyleUtils(ExcelWorkBook work) {
		titleStyle = linkStyle(work.getWorkbook());
		dataStyle = dataStyle(work.getWorkbook());
		nameStyle = nameStyle(work.getWorkbook());
		linkStyle = linkStyle(work.getWorkbook());
	}
	/**
	 *  
	 * @return HSSFCellStyle
	 */
	private static HSSFCellStyle linkStyle(HSSFWorkbook work) {
		HSSFCellStyle linkStyle = work.createCellStyle();
		  linkStyle.setBorderBottom((short)1);
		  linkStyle.setBorderLeft((short)1);
		  linkStyle.setBorderRight((short)1);
		  linkStyle.setBorderTop((short)1);
		  linkStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		  linkStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		  HSSFFont font = work.createFont();
		  font.setFontName(HSSFFont.FONT_ARIAL);
		  font.setUnderline((byte)1);
		  font.setColor(HSSFColor.BLUE.index);
		  linkStyle.setFont(font);
		  return linkStyle;
	}
	
	/**s
	 *  
	 * @return HSSFCellStyle
	 */
	private static HSSFCellStyle nameStyle(HSSFWorkbook work) {
		HSSFCellStyle nameStyle = work.createCellStyle();
		  nameStyle.setBorderBottom((short)1);
		  nameStyle.setBorderLeft((short)1);
		  nameStyle.setBorderRight((short)1);
		  nameStyle.setBorderTop((short)1);
		  nameStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
		  nameStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		  return nameStyle;
	}
	
	/**
	 *  
	 * @return HSSFCellStyle
	 */
	private static HSSFCellStyle dataStyle(HSSFWorkbook work) {
		HSSFCellStyle dataStyle = work.createCellStyle();
		  dataStyle.setBorderBottom((short)1);
		  dataStyle.setBorderLeft((short)1);
		  dataStyle.setBorderRight((short)1);
		  dataStyle.setBorderTop((short)1);
		  dataStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
		  dataStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		  dataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		  return dataStyle;
	}
	
	/**
	 *  
	 * @return HSSFCellStyle
	 */
	private static HSSFCellStyle titleStyle(HSSFWorkbook work) {
		HSSFCellStyle titleStyle = work.createCellStyle();
		font = work.createFont();
		font.setItalic(true);
	    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    font.setColor(HSSFColor.BLUE.index);
		  titleStyle.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);
		  titleStyle.setBorderLeft((short)1);
		  titleStyle.setBorderRight((short)1);
		  titleStyle.setBorderTop(HSSFCellStyle.BORDER_DOUBLE);
		  titleStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
		  titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		  return titleStyle;
	}
}

  
   5. Excel 플랜트 클래스 만들기
/**
 *  Excel 
 * @author Administrator
 *
 */
public class ExcelUtilFactory {
	
	private static ExcelUtilFactory instance = null;
	private static HttpServletRequest excelRequest = null;
	private static HttpServletResponse excelResponse = null;
	
	public static ExcelUtilFactory getInstance(HttpServletRequest request,
			HttpServletResponse response) {
		if(instance == null) {
			instance = new ExcelUtilFactory();
		}
		excelRequest = request;
		excelResponse = response;
		return instance;
	}
	
	public static void outputExcel(String excelName, List list, String[] firstRowValue) {
		ExcelWorkBook work = new ExcelWorkBook();
		work.setWorkbookName(excelName);
		ExcelSheetRow sheetRow = new ExcelSheetRow();
		ExcelSheetCell sheetCell = new ExcelSheetCell();
		ExcelCellStyleUtils util = new ExcelCellStyleUtils(work);
		sheetCell.createCurrRowTitle(sheetRow, work, firstRowValue, util.titleStyle);
		sheetCell.createCurrRowRecord(sheetRow, work, list, util.nameStyle);
		String realPath = getExcelRealPath(excelName);
//		String realPath = "e:/temp/testRealPath_2.xls";
		work.writerFileStream(realPath);
		downloadFile(realPath);
	}
	
	private static String getExcelRealPath(String excelName) {
		String realPath = excelRequest.getRealPath("/UploadFile");
		File excelFile = new File(realPath);
		if(!excelFile.exists()) {
			excelFile.mkdirs();
		}
		excelName = realPath+ "\\" + excelName+".xls";
		return  excelName;
	} 
	
	private static void downloadFile(String strfileName) {
		try {
			//  ServletContext 
			if(excelFileNotFund(strfileName)) {
				throw new IllegalArgumentException("File=["+strfileName+"] not fund file path");
			}
			//  
			File excelFile = getExcelDownloadPath(strfileName);
			putResponseStream(strfileName, excelFile);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	private static File getExcelDownloadPath(String excelName) {
//		String realPath = excelRequest.getRealPath("/UploadFile");
//		excelName = realPath+ "\\" + excelName;
//		excelName = replaceRNAll(excelName);
		File excelFile = new File(excelName);
		return  excelFile;
	}
	
	// 
	private static boolean excelFileNotFund(String strfileName) {
		return strfileName ==  null|| strfileName.equals("");
	}
	
	/**
	 * 
	 * @param strfileName :  
	 * @param excelName  :  
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static void putResponseStream(String strfileName, File excelName)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		strfileName = URLEncoder.encode(strfileName, "UTF-8");
		excelResponse.setHeader("Content-disposition","attachment; filename=" + strfileName);
		excelResponse.setContentLength((int) excelName.length());
		excelResponse.setContentType("application/x-download");
		byte[] buffer = new byte[1024];
		int i = 0;
		FileInputStream fis = new FileInputStream(excelName);
		while ((i = fis.read(buffer)) > 0) {
			JspWriter out = null;
			excelResponse.getOutputStream().write(buffer, 0, i);
		}
	}
	
	public static void main(String[] args) {
		long beginTime = System.currentTimeMillis();
		System.out.println(" :"+beginTime/1000);
		List beanList = new ArrayList();
		String[] excelTitle = new String[10];
		excelTitle[0] = " ";
		excelTitle[1] = " ";
		excelTitle[2] = " (NAV)";
		excelTitle[3] = " (%)";
		excelTitle[4] = " ";
		excelTitle[5] = " ";
		excelTitle[6] = " ";
		excelTitle[7] = " (NAV)";
		excelTitle[8] = " (%)";
		excelTitle[9] = " ";
		String[] beanArr = new String[10];
		for (int i = 0; i < 55000; i++) {
			beanArr[0] = String.valueOf(i+1);
			beanArr[1] = " A"+i;
			beanArr[2] = "1.0427";
			beanArr[3] = "-2.7514%";
			beanArr[4] = "1.1558";
			beanArr[5] = String.valueOf(i+1);
			beanArr[6] = " A"+i;
			beanArr[7] = "1.0427";
			beanArr[8] = "-2.7514%";
			beanArr[9] = "1.1558";
			beanList.add(beanArr);
		}
		outputExcel(" _factory", beanList, excelTitle);
		long endTime = System.currentTimeMillis();
		System.out.println(" 55000, "+(endTime-beginTime)/1000+" , ");
	}
}

 
다음은 Excel을 만드는 모든 도구 클래스입니다. 잘 부탁드립니다!!!!!
본인 msn:[email protected]

좋은 웹페이지 즐겨찾기