首先,介紹一下apach-poi:
Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft
Office格式檔案讀和寫的功能。
在這裏我需要導入poi所需jar包:
poi-3.10.1-20140818.jar
poi-excelant-3.10.1-20140818.jar
poi-ooxml-3.10.1-20140818.jar
poi-ooxml-schemas-3.10.1-20140818.jar
Export.java範例:
/**
* 數據導出
* @param title
* 表格標題名
* @param headers
* 表格屬性列名數組
* @param dataset
* 需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。此方法支持的
* javabean屬性的數據類型有基本數據類型及String,Date,byte[](圖片數據)
* @param pattern
* 如果有時間數據,設定輸出格式。默認爲"yyy-MM-dd"
*/
public static void exportExcel(HSSFWorkbook workbook, String fileName, int status, String[] headers,
List<String> rheaders, List<Map<String, Object>> dataset, String pattern) {
// 生成一個表格
HSSFSheet sheet = workbook.createSheet(fileName+System.currentTimeMillis());
// 設置表格默認列寬度爲15個字節
sheet.setDefaultColumnWidth(15);
// 生成一個樣式
HSSFCellStyle styleTitle = workbook.createCellStyle();
// 設置這些樣式
styleTitle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleTitle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleTitle.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleTitle.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字體應用到當前的樣式
styleTitle.setFont(font);
// 生成一個樣式
//產生表格標題行
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < rheaders.size(); i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(styleTitle);
HSSFRichTextString text = new HSSFRichTextString(rheaders.get(i));
cell.setCellValue(text);
}
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//遍歷集合數據,產生數據行
Iterator<Map<String, Object>> it = dataset.iterator();
int index = 0;
TreeMap<String, String> tt = InvokeConstant.getInvokeTitle(status);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
Map<String, Object> t = it.next();
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
try {
Object value = t.get(tt.get(headers[i]));
if(value == null){
value = "--";
}
HSSFRichTextString richString = new HSSFRichTextString();
HSSFFont font3 = workbook.createFont();
richString.applyFont(font3);
cell.setCellValue(value.toString());
} catch (SecurityException e) {
e.printStackTrace();
}catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
}
HSSFWorkbook以傳參的形式,爲了創建多個sheet,在實際情況下,可能單個請求要求導出多個結果集,不能返回多個輸出流,這個時候我想的辦法就是,excel多sheet的形式導出多個結果集,在遍歷結果集之前創建HSSFWorkbook對象,上面實例就是每次創建一個sheet。我們將數據塞完之後,就可以使用workBook.write(out),瀏覽器直接接收輸出流,這個時候我們就完成了excel導出。