利用Apache开源组件poi-3.15导出Excel表

来源:互联网 发布:知乎 赞同超过1000 编辑:程序博客网 时间:2024/06/16 05:31
package bl.poi.util;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.swing.JOptionPane;


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 bl.poi.bean.Students;


/**
 * 利用Apache开源组件poi-3.15导出Excel表
 * 
 * @author Ms dong
 * 
 * @param <T>
 *            应用泛型,适合任何一种javaBean
 */
public class ExportExcel<T> {


public void exportExcel(String[] headers, Collection<T> dataset,
OutputStream out) {
exportExcel("测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");
}


/**

* @param title
*            表格标题名

* @param headers
*            表格属性列名数组

* @param dataset
*            需要导出的数据

* @param out
*            输出流

* @param pattern
*            如果有时间数据,设定输出格式。默认为“yyy-MM-dd”
*/
@SuppressWarnings("deprecation")
public void exportExcel(String title, String[] headers,
Collection<T> dataset, OutputStream out, String pattern) {


// 申明一个工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格的默认列宽为15个字节
sheet.setDefaultColumnWidth(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.LIGHT_YELLOW.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 (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
// HSSFRichTextString text = new HSSFRichTextString(headers[i]);
// cell.setCellValue(text);
cell.setCellValue(headers[i]);
}


// 遍历集合产生标题行


Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用get方法获得属性值
Field[] fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
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);


@SuppressWarnings("unchecked")
Class<T> tCls = (Class<T>) t.getClass();
try {
Method getmethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getmethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} else {
textValue = value.toString();
}


// 如果不是图片数据,就利用正则表达式判断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.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}


} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}


}
}

try {
workbook.write(out);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}


}

public static void main(String[] args) {
// 测试学生
ExportExcel<Students> ex = new ExportExcel<Students>();
String[] headers = { "学号", "姓名", "年龄", "性别", "出生日期" };
List<Students> dataset = new ArrayList<Students>();
dataset.add(new Students("10000001", "张三", 20, "男", new Date()));
dataset.add(new Students("20000002", "李四", 24, "男", new Date()));
dataset.add(new Students("30000003", "王五", 22, "男", new Date()));
try {
OutputStream out = new FileOutputStream("E://a.xls");
ex.exportExcel(headers, dataset, out);
out.close();
JOptionPane.showMessageDialog(null, "导出成功!");
System.out.println("excel导出成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}


参考:http://www.cnblogs.com/xwdreamer/archive/2011/07/20/2296975.html

0 0