1. 程式人生 > >POI匯出資料到Excel的多個Sheet

POI匯出資料到Excel的多個Sheet

Apache POI是Apache軟體基金會的開放原始碼函式庫,POI提供API給Java程式對Microsoft Office格式檔案讀和寫的功能。

一、PSGInfoSearchAction.java中設定response返回引數

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

	/**
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward psgInfoView(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
        	
        	response.reset();// 清空response   
        	response.addHeader("Content-Disposition", "attachment;filename="+fileName);// 設定response的Header 
        	response.setContentType("application/octet-stream");
        	PoiExportExcel.PoiWriteExcel("工作薄",psgList,request,response);
        	return null;
			
        }
		return mapping.findForward("psgInfo");//跳轉到統計頁面
	}	 	
   
}

二、PoiExportExcel.java組裝資料與Excel匯出格式
package com.sasis.util;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import com.sasis.model.PSGInfoSearchForReport;
public class PoiExportExcel {
 
 /**
  * 匯出資料到多個sheet
  * @param title
  * @param list
  * @param os
  * add by bcao 2015-8-13
  */
 @SuppressWarnings({ "deprecation", "rawtypes", "unused", "unchecked" })
public static void PoiWriteExcel(String title,List list,HttpServletRequest request,HttpServletResponse response){
 	 OutputStream os=null;  
  try{
	 int sheetNum=1;//工作薄sheet編號
	 int bodyRowCount=1;//正文內容行號
	 int currentRowCount=1;//當前的行號
	 int perPageNum = 50000;//每個工作薄顯示50000條資料
	 os = new BufferedOutputStream(response.getOutputStream());//輸出流
 	 HSSFWorkbook workbook = new HSSFWorkbook();//建立excel
	 HSSFSheet sheet = workbook.createSheet(title+sheetNum);//建立一個工作薄
	 setSheetColumn(sheet);//設定工作薄列寬
	 HSSFRow row = null;//建立一行
	 HSSFCell cell = null;//每個單元格
		  
	 HSSFCellStyle titleCellStyle = createTitleCellStyle(workbook);
	 writeTitleContent(sheet,titleCellStyle);//寫入標題
	 
	//第二行開始寫入資料
	ArrayPageList pageList = (ArrayPageList) list;
	ArrayList<PSGInfoSearchForReport> psgInfos = new ArrayList<PSGInfoSearchForReport>();
	psgInfos = (ArrayList<PSGInfoSearchForReport>) pageList.getList();	 
	HSSFCellStyle bodyCellStyle = createBodyCellStyle(workbook); 
    HSSFCellStyle dateBobyCellStyle = createDateBodyCellStyle(workbook);
	for(int i=0;i<psgInfos.size();i++){
		//正文內容
		row = sheet.createRow(bodyRowCount);        
		//第二行寫開始寫入正文內容
		cell = row.createCell((short)0);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(currentRowCount);//序號
		cell = row.createCell((short)1);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getPsg_name_cn());//姓名
		cell = row.createCell((short)2);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getTel_num());//手機號
		cell = row.createCell((short)3);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getFlt_num());//航班號
		cell = row.createCell((short)4);
		cell.setCellStyle(dateBobyCellStyle);
		cell.setCellValue(psgInfos.get(i).getFlt_date());//航班日期
		cell = row.createCell((short)5);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getOrig());//始發
		cell = row.createCell((short)6);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getDest());//到達
		cell = row.createCell((short)7);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getEt_num());//電子票號
		cell = row.createCell((short)8);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getCertNo());//證件號
		cell = row.createCell((short)9);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getMain_classXls());//主艙
		cell = row.createCell((short)10);
		cell.setCellStyle(bodyCellStyle);
		cell.setCellValue(psgInfos.get(i).getSell_class());//子艙
		cell = row.createCell((short)11);
		cell.setCellStyle(bodyCellStyle);	
		cell.setCellValue(psgInfos.get(i).getSeat_no());//座位
		cell = row.createCell((short)12);
		cell.setCellStyle(bodyCellStyle);	
		cell.setCellValue(psgInfos.get(i).getStatus());//狀態
		cell = row.createCell((short)13);
		cell.setCellStyle(bodyCellStyle);	
		cell.setCellValue(psgInfos.get(i).getBags());//行李數
		cell = row.createCell((short)14);
		cell.setCellStyle(bodyCellStyle);	
		cell.setCellValue(psgInfos.get(i).getBagwht());//行李重
		cell = row.createCell((short)15);
		cell.setCellStyle(bodyCellStyle);	
		cell.setCellValue(psgInfos.get(i).getAllSpecialStr());//特殊	
		if(currentRowCount % perPageNum == 0){//每個工作薄顯示50000條資料
			sheet=null;
			sheetNum++;//工作薄編號遞增1
			sheet = workbook.createSheet(title+sheetNum);//建立一個新的工作薄
			setSheetColumn(sheet);//設定工作薄列寬
			bodyRowCount = 0;//正文內容行號置位為0
			writeTitleContent(sheet,titleCellStyle);//寫入標題			
		}
		bodyRowCount++;//正文內容行號遞增1
		currentRowCount++;//當前行號遞增1
	}
	   CookieUtil.remove(request,response,"exporting");//刪除exporting cookie
	   workbook.write(os);
	   os.flush();
	 }catch(Exception e){
		   e.printStackTrace();
	 } finally {
		try {
			 os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
	 }
		 
	}
 	/**
 	 * 設定正文單元樣式
 	 * @param workbook
 	 * @return
 	 */
 	public static HSSFCellStyle createBodyCellStyle(HSSFWorkbook workbook){ 
 		HSSFCellStyle cellStyle = workbook.createCellStyle();
 		HSSFFont font = workbook.createFont();
 		font.setFontHeightInPoints((short) 8);  
 		font.setFontName(HSSFFont.FONT_ARIAL);//設定標題字型
 		cellStyle.setFont(font);
 		cellStyle = workbook.createCellStyle();
 		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中 		
 		return cellStyle;
 	}
 	/**
 	 * 設定正文單元時間樣式
 	 * @param workbook
 	 * @return
 	 */
 	public static HSSFCellStyle createDateBodyCellStyle(HSSFWorkbook workbook){ 
 		HSSFCellStyle cellStyle = workbook.createCellStyle();
 		HSSFFont font = workbook.createFont();
 		font.setFontHeightInPoints((short) 8);  
 		font.setFontName(HSSFFont.FONT_ARIAL);//設定標題字型
 		cellStyle.setFont(font);
 		cellStyle = workbook.createCellStyle();
 		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中 	
 	    HSSFDataFormat format= workbook.createDataFormat();
 	    cellStyle.setDataFormat(format.getFormat("yyyy-mm-dd"));  		
 		return cellStyle;
 	} 	

 	/**
 	 * 設定標題單元樣式
 	 * @param workbook
 	 * @return
 	 */
 	public static HSSFCellStyle createTitleCellStyle(HSSFWorkbook workbook){ 
 		HSSFCellStyle cellStyle = workbook.createCellStyle();
 		HSSFFont font = workbook.createFont();
 		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
 		font.setFontHeightInPoints((short) 8);  
 		font.setFontName(HSSFFont.FONT_ARIAL);//設定標題字型
 		cellStyle.setFont(font);
 		cellStyle = workbook.createCellStyle();
 		cellStyle.setFont(font);//設定列標題樣式
 		cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);// 設定背景色
 		cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
 		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中 		
 		return cellStyle;
 	} 	
 	/**
 	 * 寫入標題行
 	 * @param workbook
 	 * @return
 	 */
 	public static void writeTitleContent (HSSFSheet sheet,HSSFCellStyle cellStyle){ 
 		HSSFRow row = null;
 		HSSFCell cell = null;		
 		//標題
 		row = sheet.createRow(0);        
 		//第一行寫入標題行
 		cell = row.createCell((short)0);//序號
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("序號");
 		cell = row.createCell((short)1);//姓名
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("姓名");
 		cell = row.createCell((short)2);//手機號
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("手機號");
 		cell = row.createCell((short)3);//航班號
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("航班號");
 		cell = row.createCell((short)4);//航班日期
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("航班日期");
 		cell = row.createCell((short)5);//始發
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("始發");
 		cell = row.createCell((short)6);//到達
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("到達");
 		cell = row.createCell((short)7);//電子票號
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("電子票號");
 		cell = row.createCell((short)8);//證件號
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("證件號");
 		cell = row.createCell((short)9);//主艙
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("主艙");
 		cell = row.createCell((short)10);//子艙
 		cell.setCellStyle(cellStyle);
 		cell.setCellValue("子艙");
 		cell = row.createCell((short)11);//座位
 		cell.setCellStyle(cellStyle);	
 		cell.setCellValue("座位");
 		cell = row.createCell((short)12);//狀態
 		cell.setCellStyle(cellStyle);	
 		cell.setCellValue("狀態");
 		cell = row.createCell((short)13);//行李數
 		cell.setCellStyle(cellStyle);	
 		cell.setCellValue("行李數");
 		cell = row.createCell((short)14);//行李重
 		cell.setCellStyle(cellStyle);	
 		cell.setCellValue("行李重");
 		cell = row.createCell((short)15);//特殊
 		cell.setCellStyle(cellStyle);	
 		cell.setCellValue("特殊");
 	}
 	public static void setSheetColumn(HSSFSheet sheet){
		 sheet.setColumnWidth((short) 2, (short) 3200);//設定手機號列寬
 		 sheet.setColumnWidth((short) 4, (short) 3200);//設定航班日期列寬
 		 sheet.setColumnWidth((short) 7, (short) 5250);//設定電子票號列寬
 		 sheet.setColumnWidth((short) 8, (short) 6250);//設定證件號列寬
 	}
 		
}
三、匯出的Excel檔案