package com.wy.common.util;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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 org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
//這是一個導出Excel的工具類
public class ExportExcelUtils{
/**
* 這是一個通用的方法,將一個map集合作爲表格內容輸入到excel中
*
* @param title
* 表格標題名
* @param headers
* 表格屬性列名數組
* @param rows
* 需要顯示的數據集合,row爲List
@SuppressWarnings("deprecation")
public void exportExcel(String title, String[] headers,List<Map> rows, String[] rowkeys, OutputStream out) {
// 聲明一個工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = workbook.createSheet(title);
// 設置表格默認列寬度爲15個字節
sheet.setDefaultColumnWidth((short) 25);
if(rows!=null && rows.size()>0 ){
//判斷傳入集合數據,如爲空即不填充數據導出空Excel
/** ----------- 生成標題 ------------*/
//第一行寫入標題
HSSFFont fontTitle = workbook.createFont();
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
fontTitle.setFontHeightInPoints((short) 16);
titleStyle.setFont(fontTitle);
if(headers!=null){
//這裏作非空驗證
sheet.addMergedRegion(new Region(0,(short)0,0,(short)(headers.length-1)));
}
HSSFRow rowTitle = sheet.createRow(0);
rowTitle.setHeight((short)500);
HSSFCell cellTitle = rowTitle.createCell(0);
cellTitle.setCellStyle(titleStyle);
cellTitle.setCellValue(title);
/** ----------- 生成表頭 ------------*/
HSSFFont fontHeader = workbook.createFont();
fontHeader.setBoldweight(Font.BOLDWEIGHT_BOLD);
HSSFCellStyle cstyleHeader =workbook.createCellStyle();
cstyleHeader.setFont(fontHeader);
cstyleHeader.setAlignment(CellStyle.ALIGN_CENTER);
cstyleHeader.setBorderBottom(CellStyle.BORDER_THIN);
cstyleHeader.setBorderLeft(CellStyle.BORDER_THIN);
cstyleHeader.setBorderRight(CellStyle.BORDER_THIN);
cstyleHeader.setBorderTop(CellStyle.BORDER_THIN);
HSSFRow row = sheet.createRow(1);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
//cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellStyle(cstyleHeader);
cell.setCellValue(text);
}
/** ----------- 生成數據行 ------------*/
int index = 2;
HSSFFont fontData = workbook.createFont();
fontData.setBoldweight(Font.BOLDWEIGHT_NORMAL);
HSSFCellStyle cstyleData =workbook.createCellStyle();
cstyleData.setBorderBottom(CellStyle.BORDER_THIN);
cstyleData.setBorderLeft(CellStyle.BORDER_THIN);
cstyleData.setBorderRight(CellStyle.BORDER_THIN);
cstyleData.setBorderTop(CellStyle.BORDER_THIN);
cstyleData.setFont(fontData);
cstyleData.setAlignment(CellStyle.ALIGN_CENTER);
/* HSSFCellStyle cstyleData1 =workbook.createCellStyle();
cstyleData1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cstyleData1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cstyleData1.setBorderRight(HSSFCellStyle.BORDER_THIN);
cstyleData1.setBorderTop(HSSFCellStyle.BORDER_THIN);
cstyleData1.setFont(fontData);
cstyleData1.setAlignment(HSSFCellStyle.ALIGN_LEFT);*/
for(Map row1 : rows){
row = sheet.createRow(index);
//獲取map的所有需要導入到excel中數據key值
for(int i = 0 ; i < rowkeys.length ; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(cstyleData);
String key = rowkeys[i];
String cellValue="";
if(row1.get(key)!=null){
cellValue =row1.get(key).toString();
}
else{
cellValue="";
}
cell.setCellValue(cellValue);
}
index++;
}
/** ----------- 生成說明行 ------------*/
HSSFFont fontDesc = workbook.createFont();
HSSFCellStyle descStyle =workbook.createCellStyle();
descStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
descStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
descStyle.setAlignment(CellStyle.ALIGN_LEFT);
descStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
fontDesc.setFontHeightInPoints((short) 9);
descStyle.setFont(fontDesc);
//最後行寫入描述
/*
sheet.addMergedRegion(new Region(index,(short)0,index,(short)(headers.length-1)));
HSSFRow rowDesc = sheet.createRow(index);
rowDesc.setHeight((short)1500);
HSSFCell cellDesc = rowDesc.createCell(0);
cellDesc.setCellStyle(descStyle);
descStyle.setWrapText(true);
cellDesc.setCellValue(new HSSFRichTextString(conditionsDescrip));
*/
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*Action層中的方法*/
public String exportQuesByTypeAndId(){
try {
ExportExcelUtils<T> ex = new ExportExcelUtils<T>();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 獲取查詢數據
List<Map> rows = null;
String questionnaireId = ServletActionContext.getRequest().getParameter("questionnaireId");
TbInteractionQuestionnaire tbQuestionnaire=(TbInteractionQuestionnaire) questionnaireService.getDataBaseDao().load(TbInteractionQuestionnaire.class, questionnaireId);
String type=ServletActionContext.getRequest().getParameter("type");
rows = questionnaireService.exportQuesByTypeAndId(questionnaireId,type);
int i=0;
String name=tbQuestionnaire.getQuestionnaireTitle()+"_參與人員_"+DataConvertUtil.getCurrentDate();
if(rows!=null && rows.size()>0 && rows.get(0)!=null){
//headers 表示excel首行標題
String[] headers =new String[rows.get(0).size()];
//rowkeys 表示excel填充數據行對應的key
String[] rowkeys =new String[rows.get(0).size()];
System.out.println(rows.size());
Iterator ita = rows.get(0).entrySet().iterator();
while(ita.hasNext()){
/*這裏面我將數據庫查詢出的數據字段名稱
替換成對應中文作爲Excel每列標題,將字段
名稱直接作爲數據行的key,分別將標題和
key存放在數組中,這裏大家可以自定義
Excel的每列標題,key可以直接取庫中
字段名稱。
*/
Entry entry = (Entry)ita.next();
headers[i]=entry.getKey().toString().replaceAll("userAccount","工號/學號").replaceAll("orgName","部門").replaceAll("persontype", "類別").replaceAll("voteFlag","參與狀態");
rowkeys[i]=entry.getKey().toString();
i++;
}
ex.exportExcel(name, headers, rows,
rowkeys,bos);
}
else{
/*
這裏當數據集爲空則傳入null,
輸出流對象必輸傳
*/
ex.exportExcelNoAnswerForQues(name
,null, null,null,bos);
}
byte[] fileBytes = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(fileBytes);
bos.close();
inputStream = bis;
//這裏fileName指定爲文件的名稱(全局變量需要給出相應的getter,setter方法)
fileName = new String((name + ".xls").getBytes(),"ISO-8859-1");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
rspCode = RtnCodeConstant.RTN_CODE_UNKNOW_ERROR;
e.printStackTrace();
}
return SUCCESS;
}
//這裏是struts的配置
<action name="exportQuesByTypeAndId"
class="queryQuertionnaireAction"
method="exportQuesByTypeAndId">
<result type="stream">
<param name="noCache">true</param>
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">false</param>
</result>
<result name="noSession">/jsps/login/no_session.jsp
</result>
</action>
//下圖爲數據庫 中查詢的數據
//注:導出excel需通過location.href 的方式直接請求後臺方法,或者使用表單提交方式