JAvaエクスポートexcelをツールクラスにカプセル化


いくつかのプログラムを開発する中で往々にしてexcelをエクスポートする需要に遭遇し、ネット上の多くの例をよく見て、以下に共通のツールクラスを示します.
ExportExcel.java
package cn.hx.as.util;


import java.io.File;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.lang.reflect.Field;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/***
 * @author ardp
 */
public class ExportExcel {
	/***************************************************************************
	 * @param fileName
	 *            EXCEL    
	 * @param listTitle
	 *            EXCEL          
	 * @param listContent
	 *            EXCEL        
	 * @return
	 */
	public final static String exportExcel(String fileName, String[] Title,
			Object listContent, HttpServletResponse response,String title,Integer colWidth) {
		String result = "    :Excel      !";
		//        EXCEL
		try {
			//      ,         ______________________begin
			OutputStream os = response.getOutputStream();//      
			response.reset();//      
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(fileName.getBytes("GB2312"), "ISO8859-1"));
			//        
			response.setContentType("application/msexcel");//       
			//      ,         _______________________end

			/** **********     ************ */
			WritableWorkbook workbook = Workbook.createWorkbook(os);
			/** **********     ************ */

			WritableSheet sheet = workbook.createSheet("Sheet1", 0);

			/** **********      (     )、   ***************** */
			jxl.SheetSettings sheetset = sheet.getSettings();
			sheetset.setProtected(false);

			/** ************       ************** */
			WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);

			/** ************           ,    ************ */
			//       
			WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
			wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); //   
			wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); //       
			wcf_center.setAlignment(Alignment.CENTRE); //       
			wcf_center.setWrap(false); //       

			//       
			WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
			wcf_left.setBorder(Border.NONE, BorderLineStyle.THIN); //   
			wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); //       
			wcf_left.setAlignment(Alignment.LEFT); //       
			wcf_left.setWrap(true); //       
			/** ***************   EXCEL     ,  ********************* */
			/** ***************   EXCEL     ,    ********************* */
			 if(colWidth == null){
				 colWidth=21; 
			 }
			 sheet.mergeCells(0, 0, colWidth, 0);
			 sheet.addCell(new Label(0, 0, title, wcf_center));
			/** ***************   EXCEL      ********************* */
			for (int i = 0; i < Title.length; i++) {
				sheet.setColumnView(i, Title.length+6);//    
				sheet.addCell(new Label(i, 1, Title[i], wcf_center));
			}
			/** ***************   EXCEL    ********************* */
			Field[] fields = null;
			int i = 2;
			for (Object obj : (List)listContent) {
				fields = obj.getClass().getDeclaredFields();
				int j = 0;
				for (Field v : fields) {
					v.setAccessible(true);
					Object va = v.get(obj);
					if (va == null) {
						va = "";
					}
					SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					if(va instanceof Timestamp||va instanceof Date){
						sheet.addCell(new Label(j, i, sf.format(va), wcf_left));
					}else{
						sheet.addCell(new Label(j, i, va.toString(), wcf_left));
						
					}

					j++;

				}

				i++;

			}

			/** **********           EXCEL   ******** */

			workbook.write();

			/** *********    ************* */

			workbook.close();

		} catch (Exception e) {

			result = "    :Excel      ,  :" + e.toString();

			System.out.println(result);

			e.printStackTrace();

		}

		return result;

	}
	
	/***************************************************************************
	 * @param fileName
	 *            EXCEL    
	 * @param listTitle
	 *            EXCEL          
	 * @param listContent
	 *            EXCEL        
	 * @return
	 */
	public final static String exportExcel1(File file,String fileName, String[] Title,
			Object listContent, HttpServletResponse response,String title,Integer colWidth) {
		String result = "    :Excel      !";
		//        EXCEL
		try {
			//      ,         ______________________begin
			OutputStream os = response.getOutputStream();//      
			response.reset();//      
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(fileName.getBytes("GB2312"), "ISO8859-1"));
			//        
			response.setContentType("application/msexcel");//       
			//      ,         _______________________end

			/** **********     ************ */
			WritableWorkbook workbook = Workbook.createWorkbook(file);
//			WritableWorkbook workbook = Workbook.createWorkbook(os);
			/** **********     ************ */

			WritableSheet sheet = workbook.createSheet("Sheet1", 0);

			/** **********      (     )、   ***************** */
			jxl.SheetSettings sheetset = sheet.getSettings();
			sheetset.setProtected(false);

			/** ************       ************** */
			WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);

			/** ************           ,    ************ */
			//       
			WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
			wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); //   
			wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); //       
			wcf_center.setAlignment(Alignment.CENTRE); //       
			wcf_center.setWrap(false); //       

			//       
			WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
			wcf_left.setBorder(Border.NONE, BorderLineStyle.THIN); //   
			wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); //       
			wcf_left.setAlignment(Alignment.LEFT); //       
			wcf_left.setWrap(true); //       
			/** ***************   EXCEL     ,  ********************* */
			/** ***************   EXCEL     ,    ********************* */
			 if(colWidth == null){
				 colWidth=21; 
			 }
			 sheet.mergeCells(0, 0, colWidth, 0);
			 sheet.addCell(new Label(0, 0, title, wcf_center));
			/** ***************   EXCEL      ********************* */
			for (int i = 0; i < Title.length; i++) {
				sheet.setColumnView(i, Title.length+6);//    
				sheet.addCell(new Label(i, 1, Title[i], wcf_center));
			}
			/** ***************   EXCEL    ********************* */
			Field[] fields = null;
			int i = 2;
			for (Object obj : (List)listContent) {
				fields = obj.getClass().getDeclaredFields();
				int j = 0;
				for (Field v : fields) {
					v.setAccessible(true);
					Object va = v.get(obj);
					if (va == null) {
						va = "";
					}
					SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					if(va instanceof Timestamp||va instanceof Date){
						sheet.addCell(new Label(j, i, sf.format(va), wcf_left));
					}else{
						sheet.addCell(new Label(j, i, va.toString(), wcf_left));
						
					}

					j++;

				}

				i++;

			}

			/** **********           EXCEL   ******** */

			workbook.write();

			/** *********    ************* */

			workbook.close();

		} catch (Exception e) {

			result = "    :Excel      ,  :" + e.toString();

			System.out.println(result);

			e.printStackTrace();

		}

		return result;

	}

}

Controller制御クラスまたはサービスでの呼び出し方法:
public void createProudctPriceExcel(HttpServletRequest request,HttpServletResponse response){
		List excellist=new ArrayList();
		//Map map=(Map)productPrices;
		//System.out.println("size"+map.size());
		ProductExl productExl=null;
		//Set keys = map.keySet();
		for(int i=0;i map = (Map)productPrices.get(i);
			Set keys = map.keySet();
			for(String key:keys){
				if(key.equals("pname")){
					productExl.setPname(map.get(key).toString());
				}
				if(key.equals("total")){
					productExl.setTotal(map.get(key).toString());
				}
				
			}
			excellist.add(productExl);
		}
		String[] Title = { "    ","    (  : )"};
		ExportExcel.exportExcel(new Date().getTime() + ".xls", Title, excellist,
				response, "        ", 1);
	}

必要なjarパッケージ:jxl-2.6.6.jar