須要的jar org.apache.poi.jarjava
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>正則表達式
package com.iflytek.reception.common.util;apache
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.SimpleDateFormat;數組
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;網絡
public class ExportExcel<T> {
public void exportExcel(Collection<T> dataset, OutputStream out) {
exportExcel("測試POI導出EXCEL文檔", null, dataset, out, "yyyy-MM-dd");
}
public void exportExcel(String[] headers, Collection<T> dataset, OutputStream out) {
exportExcel("測試POI導出EXCEL文檔", headers, dataset, out, "yyyy-MM-dd");
}
public void exportExcel(String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
exportExcel("測試POI導出EXCEL文檔", headers, dataset, out, pattern);
}
/**
* 這是一個通用的方法,利用了JAVA的反射機制,能夠將放置在JAVA集合中而且符號必定條件的數據以EXCEL 的形式輸出到指定IO設備上
*
* @param title
* 表格標題名
* @param headers
* 表格屬性列名數組
* @param dataset
* 須要顯示的數據集合,集合中必定要放置符合javabean風格的類的對象。此方法支持的
* javabean屬性的數據類型有基本數據類型及String,Date,byte[](圖片數據)
* @param out
* 與輸出設備關聯的流對象,能夠將EXCEL文檔導出到本地文件或者網絡中
* @param pattern
* 若是有時間數據,設定輸出格式。默認爲"yyy-MM-dd"
*/
@SuppressWarnings("unchecked")
public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
// 聲明一個工做薄
@SuppressWarnings("resource")
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = workbook.createSheet(title);
// 設置表格默認列寬度爲15個字節
sheet.setDefaultColumnWidth((short)15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
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);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short)12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字體應用到當前的樣式
style.setFont(font);
// 生成並設置另外一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.WHITE.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另外一個字體
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應用到當前的樣式
style2.setFont(font2);
// 聲明一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定義註釋的大小和位置,詳見文檔
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short)6, 5));
// 設置註釋內容
comment.setString(new HSSFRichTextString("能夠在POI中添加註釋!"));
// 設置註釋做者,當鼠標移動到單元格上是能夠在狀態欄中看到該內容.
comment.setAuthor("leno");
//產生表格標題行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
@SuppressWarnings("deprecation")
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//遍歷集合數據,產生數據行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T)it.next();
//利用反射,根據javabean屬性的前後順序,動態調用getXxx()方法獲得屬性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < headers.length; i++) {
@SuppressWarnings("deprecation")
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try {
@SuppressWarnings("rawtypes")
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
//判斷值的類型後進行強制類型轉換
String textValue = null;
// if (value instanceof Integer) {
// int intValue = (Integer) value;
// cell.setCellValue(intValue);
// } else if (value instanceof Float) {
// float fValue = (Float) value;
// textValue = new HSSFRichTextString(
// String.valueOf(fValue));
// cell.setCellValue(textValue);
// } else if (value instanceof Double) {
// double dValue = (Double) value;
// textValue = new HSSFRichTextString(
// String.valueOf(dValue));
// cell.setCellValue(textValue);
// } else if (value instanceof Long) {
// long longValue = (Long) value;
// cell.setCellValue(longValue);
// }
if (value instanceof Boolean) {
boolean bValue = (Boolean)value;
textValue = "男";
if (!bValue) {
textValue = "女";
}
}
else if (value instanceof Date) {
Date date = (Date)value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} /*else if (value instanceof byte[]) {
// 有圖片時,設置行高爲60px;
row.setHeightInPoints(60);
// 設置圖片所在列寬度爲80px,注意這裏單位的一個換算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
1023, 255, (short) 6, index, (short) 6, index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
}*/
else {
//其它數據類型都看成字符串簡單處理
textValue = BaseUtil.toString(value);
}
//若是不是圖片數據,就利用正則表達式判斷textValue是否所有由數字組成
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()) {
//是數字看成double處理
cell.setCellValue(Double.parseDouble(textValue));
}
else {
HSSFRichTextString richString = new HSSFRichTextString(textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLACK.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
finally {
}
}
}
try {
workbook.write(out);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}app
public void export(HttpServletRequest request, HttpServletResponse responset)
throws IOException {
ExportExcel<T> ex = new ExportExcel<T>();
String[] headers = {"title1", "title2", "title3", "title3", "title4"};
List<T> ssList ;
List<T> dataset = new ArrayList<T>();
for (T t: ssList) {
dataset.add(ss);
}
response.setContentType("application/binary;charset=ISO8859_1");
ServletOutputStream os = response.getOutputStream();
String fileName = new String(("住宿統計excel文件").getBytes(), "ISO8859_1");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
ex.exportExcel(headers, dataset, os);
}測試
百度別人的東西修修改改。字體