package com.jv.core.util;
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.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
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;
public class ExportExcelUtil<T> {
private DecimalFormat bf = new DecimalFormat("###,###,###.##");
//標準用例
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out,String[] headertool) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",0,headertool,null);
}
public void exportExcel(String[] headers, Collection<T> dataset,
OutputStream out) {
exportExcel("", headers, dataset, out, "yyyy-MM-dd HH:mm:ss",0,null,null);
}
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",0,null,null);
}
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out,int rowindex) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",rowindex,null,null);
}
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out,int rowindex,String[] headertool) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",rowindex,headertool,null);
}
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out,int rowindex,String[] headertool,String[] foottool) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",rowindex,headertool,foottool);
}
/**
* 这是一个通用的方法,利用了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", "resource", "deprecation", "rawtypes" })
//(标题,列标题,数据,输出,时间格式,第几行开始,标题下内容,结束行内容)
public void exportExcel(String title, String[] headers,
Collection<T> dataset, OutputStream out, String pattern,int rowindex,String[] headertool,String[] foottool) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
HSSFCellStyle tstyle = workbook.createCellStyle();
// 设置这些样式
tstyle.setFillForegroundColor(HSSFColor.WHITE.index);
tstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
tstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
tstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
tstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
tstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
tstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
tstyle.setBottomBorderColor(HSSFColor.BLACK.index);
// 生成一个字体
HSSFFont tfont = workbook.createFont();
tfont.setColor(HSSFColor.BLACK.index);
tfont.setFontHeightInPoints((short) 14);
tfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
tstyle.setFont(tfont);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.WHITE.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);
style.setBottomBorderColor(HSSFColor.BLACK.index);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.BLACK.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);
style2.setBottomBorderColor(HSSFColor.BLACK.index);
// 生成另一个字体
HSSFFont font2 = workbook.createFont();
font2.setColor(HSSFColor.BLACK.index);
// 把字体应用到当前的样式
style2.setFont(font2);
// 生成并设置另一个样式
HSSFCellStyle styleft = workbook.createCellStyle();
styleft.setFillForegroundColor(HSSFColor.WHITE.index);
styleft.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
styleft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleft.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleft.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleft.setAlignment(HSSFCellStyle.ALIGN_CENTER);
styleft.setBottomBorderColor(HSSFColor.BLACK.index);
// 声明一个画图的顶级管理器
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");
if(!title.equals("")){
//产生表格標題
HSSFRow trow = sheet.createRow(rowindex);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = trow.createCell(i);
if(i==0){
cell.setCellValue(title);
cell.setCellStyle(tstyle);
}
}
sheet.addMergedRegion(new Region(0, (short) 0, 1, (short) (headers.length-1)));
rowindex+=2;
}
if(headertool!=null){
HSSFRow rowht = sheet.createRow(rowindex);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = rowht.createCell(i);
if(i<headertool.length){
HSSFRichTextString text = new HSSFRichTextString(headertool[i]);
cell.setCellValue(text);
cell.setCellStyle(styleft);
}else{
cell.setCellValue("");
cell.setCellStyle(styleft);
sheet.addMergedRegion(new Region(rowindex, (short) i, rowindex, (short) (headers.length-1)));
}
}
//sheet.addMergedRegion(new Region(rowindex+1, (short) 0, rowindex+1, (short) (headers.length-1)));
rowindex+=1;
}
//sheet.addMergedRegion(new Region(2, (short) 1, 4, (short) 1));
// 产生表格數據标题行
HSSFRow row = sheet.createRow(rowindex);
row.setHeightInPoints((short) 18);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 是数字当作double处理
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat format= workbook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("#,##0.00"));
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
//int index = rowindex;
while (it.hasNext()) {
rowindex++;
row = sheet.createRow(rowindex);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (short 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);
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
if(value==null){
value="";
}
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, rowindex, (short) 6, rowindex);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
}else if(value instanceof Long){
textValue = value.toString();
if(value.equals("0")){
textValue="0";
}
}else if (value instanceof Float || value instanceof Double) {
textValue = bf.format(value);
cell.setCellValue(bf.format(value));
} else if (value instanceof BigDecimal) {
textValue = bf.format(((BigDecimal) value).doubleValue());
cell.setCellValue(bf.format(((BigDecimal) value).doubleValue()));
} else {
// 其它数据类型都当作字符串简单处理
textValue = value.toString();
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if (textValue != null) {
//Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Pattern p = Pattern.compile("[\\d]*[\\.][\\d]{2}"); // 小数保留两位小数
Matcher matcher = p.matcher(textValue.replace("-",""));
Pattern p1 = Pattern.compile("[\\d]*[\\.][\\d]{1}"); // 小数保留1位小数
Matcher matcher1 = p1.matcher(textValue.replace("-",""));
if (matcher.matches()) {
// 是数字当作double处理
// HSSFCellStyle cellStyle = workbook.createCellStyle();
// HSSFDataFormat format= workbook.createDataFormat();
// cellStyle.setDataFormat(format.getFormat("#,##0.00"));
// cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
// cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell.setCellStyle(cellStyle);
cell.setCellValue(Double.parseDouble(textValue));
// Double num=Double.parseDouble(textValue);
// if(num % 1.0 == 0){
// textValue.replace(".0","");System.out.println(textValue);
// cell.setCellValue(Double.parseDouble(textValue));
// }else{
// cell.setCellValue(Double.parseDouble(textValue));
// }
}else if(matcher1.matches()) {
//textValue.replace(".0","");
// HSSFCellStyle cellStyle = workbook.createCellStyle();
// HSSFDataFormat format= workbook.createDataFormat();
// cellStyle.setDataFormat(format.getFormat("#,##0.00"));
// cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
// cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell.setCellStyle(cellStyle);
cell.setCellValue(Double.parseDouble(textValue));
}else {
HSSFRichTextString richString = new HSSFRichTextString(
textValue);
// HSSFFont font3 = workbook.createFont(); zyu test
//font3.setColor(HSSFColor.BLUE_GREY.index);
// richString.applyFont(workbook.createFont());
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 {
// 清理资源
}
}
}
if(foottool!=null){
sheet.addMergedRegion(new Region(rowindex+1, (short) 0, rowindex+1, (short) (headers.length-1)));
rowindex+=2;
HSSFRow rowht = sheet.createRow(rowindex);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = rowht.createCell(i);
if(i<foottool.length){
HSSFRichTextString text = new HSSFRichTextString(foottool[i]);
cell.setCellValue(text);
}else{
sheet.addMergedRegion(new Region(rowindex, (short) i, rowindex, (short) (headers.length-1)));
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// public static void main(String[] args) {
// // 测试学生
// ExportExcelUtil<Student> ex = new ExportExcelUtil<Student>();
// String[] headers = { "学号", "姓名", "年龄", "性别", "出生日期" };
// List<Student> dataset = new ArrayList<Student>();
// dataset.add(new Student (10000001, "张三", 20, true, new Date()));
// dataset.add(new Student (20000002, "李四", 24, false, new Date()));
// dataset.add(new Student (30000003, "王五", 22, true, new Date()));
// // 测试图书
// ExportExcelUtil<Booktest> ex2 = new ExportExcelUtil<Booktest>();
// String[] headers2 = { "图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN",
// "图书出版社", "封面图片" };
// List<Booktest> dataset2 = new ArrayList<Booktest>();
// try {
// @SuppressWarnings("resource")
// BufferedInputStream bis = new BufferedInputStream(
// new FileInputStream("F://cc//01.gif"));//圖片
// byte[] buf = new byte[bis.available()];
// while ((bis.read(buf)) != -1) {
// //
// }
// dataset2.add(new Booktest(1, "jsp", "leno", 300.33f, " 1234567","清华出版社", buf));
// dataset2.add(new Booktest(2, "java编程思想", "brucl", 300.33f, " 1234567","阳光出版社", buf));
// dataset2.add(new Booktest(3, "DOM艺术", "lenotang", 300.33f, " 1234567","清华出版社", buf));
// dataset2.add(new Booktest(4, "c++经典", "leno", 400.33f, " 1234567","清华出版社", buf));
// dataset2.add(new Booktest(5, "c#入门", "leno", 300.33f, " 1234567","汤春秀出版社", buf));
//
// OutputStream out = new FileOutputStream("E://a.xls");
// OutputStream out2 = new FileOutputStream("E://b.xls");
// OutputStream out3 = new FileOutputStream("E://c.xls");
// OutputStream out4 = new FileOutputStream("E://d.xls");
// ex.exportExcel(headers, dataset, out);
// ex2.exportExcel(headers2, dataset2, out2);String test="測試";
// ex.exportExcel(test,headers, dataset, out3,2,null,null);
// String[] headerfoot = { "图书编号", "图书名称" };
// String[] foottool = { "图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN",
// "图书出版社", "封面图片" };
// ex.exportExcel(test,headers, dataset, out4,2,headerfoot,foottool);
// out.close();
// JOptionPane.showMessageDialog(null, "导出成功!");
// System.out.println("excel导出成功!");
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
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.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
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;
public class ExportExcelUtil<T> {
private DecimalFormat bf = new DecimalFormat("###,###,###.##");
//標準用例
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out,String[] headertool) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",0,headertool,null);
}
public void exportExcel(String[] headers, Collection<T> dataset,
OutputStream out) {
exportExcel("", headers, dataset, out, "yyyy-MM-dd HH:mm:ss",0,null,null);
}
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",0,null,null);
}
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out,int rowindex) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",rowindex,null,null);
}
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out,int rowindex,String[] headertool) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",rowindex,headertool,null);
}
public void exportExcel(String title,String[] headers, Collection<T> dataset,
OutputStream out,int rowindex,String[] headertool,String[] foottool) {
exportExcel(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss",rowindex,headertool,foottool);
}
/**
* 这是一个通用的方法,利用了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", "resource", "deprecation", "rawtypes" })
//(标题,列标题,数据,输出,时间格式,第几行开始,标题下内容,结束行内容)
public void exportExcel(String title, String[] headers,
Collection<T> dataset, OutputStream out, String pattern,int rowindex,String[] headertool,String[] foottool) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
HSSFCellStyle tstyle = workbook.createCellStyle();
// 设置这些样式
tstyle.setFillForegroundColor(HSSFColor.WHITE.index);
tstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
tstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
tstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
tstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
tstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
tstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
tstyle.setBottomBorderColor(HSSFColor.BLACK.index);
// 生成一个字体
HSSFFont tfont = workbook.createFont();
tfont.setColor(HSSFColor.BLACK.index);
tfont.setFontHeightInPoints((short) 14);
tfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
tstyle.setFont(tfont);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.WHITE.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);
style.setBottomBorderColor(HSSFColor.BLACK.index);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.BLACK.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);
style2.setBottomBorderColor(HSSFColor.BLACK.index);
// 生成另一个字体
HSSFFont font2 = workbook.createFont();
font2.setColor(HSSFColor.BLACK.index);
// 把字体应用到当前的样式
style2.setFont(font2);
// 生成并设置另一个样式
HSSFCellStyle styleft = workbook.createCellStyle();
styleft.setFillForegroundColor(HSSFColor.WHITE.index);
styleft.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
styleft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleft.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleft.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleft.setAlignment(HSSFCellStyle.ALIGN_CENTER);
styleft.setBottomBorderColor(HSSFColor.BLACK.index);
// 声明一个画图的顶级管理器
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");
if(!title.equals("")){
//产生表格標題
HSSFRow trow = sheet.createRow(rowindex);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = trow.createCell(i);
if(i==0){
cell.setCellValue(title);
cell.setCellStyle(tstyle);
}
}
sheet.addMergedRegion(new Region(0, (short) 0, 1, (short) (headers.length-1)));
rowindex+=2;
}
if(headertool!=null){
HSSFRow rowht = sheet.createRow(rowindex);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = rowht.createCell(i);
if(i<headertool.length){
HSSFRichTextString text = new HSSFRichTextString(headertool[i]);
cell.setCellValue(text);
cell.setCellStyle(styleft);
}else{
cell.setCellValue("");
cell.setCellStyle(styleft);
sheet.addMergedRegion(new Region(rowindex, (short) i, rowindex, (short) (headers.length-1)));
}
}
//sheet.addMergedRegion(new Region(rowindex+1, (short) 0, rowindex+1, (short) (headers.length-1)));
rowindex+=1;
}
//sheet.addMergedRegion(new Region(2, (short) 1, 4, (short) 1));
// 产生表格數據标题行
HSSFRow row = sheet.createRow(rowindex);
row.setHeightInPoints((short) 18);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 是数字当作double处理
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat format= workbook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("#,##0.00"));
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
//int index = rowindex;
while (it.hasNext()) {
rowindex++;
row = sheet.createRow(rowindex);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (short 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);
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
if(value==null){
value="";
}
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, rowindex, (short) 6, rowindex);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
}else if(value instanceof Long){
textValue = value.toString();
if(value.equals("0")){
textValue="0";
}
}else if (value instanceof Float || value instanceof Double) {
textValue = bf.format(value);
cell.setCellValue(bf.format(value));
} else if (value instanceof BigDecimal) {
textValue = bf.format(((BigDecimal) value).doubleValue());
cell.setCellValue(bf.format(((BigDecimal) value).doubleValue()));
} else {
// 其它数据类型都当作字符串简单处理
textValue = value.toString();
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if (textValue != null) {
//Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Pattern p = Pattern.compile("[\\d]*[\\.][\\d]{2}"); // 小数保留两位小数
Matcher matcher = p.matcher(textValue.replace("-",""));
Pattern p1 = Pattern.compile("[\\d]*[\\.][\\d]{1}"); // 小数保留1位小数
Matcher matcher1 = p1.matcher(textValue.replace("-",""));
if (matcher.matches()) {
// 是数字当作double处理
// HSSFCellStyle cellStyle = workbook.createCellStyle();
// HSSFDataFormat format= workbook.createDataFormat();
// cellStyle.setDataFormat(format.getFormat("#,##0.00"));
// cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
// cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell.setCellStyle(cellStyle);
cell.setCellValue(Double.parseDouble(textValue));
// Double num=Double.parseDouble(textValue);
// if(num % 1.0 == 0){
// textValue.replace(".0","");System.out.println(textValue);
// cell.setCellValue(Double.parseDouble(textValue));
// }else{
// cell.setCellValue(Double.parseDouble(textValue));
// }
}else if(matcher1.matches()) {
//textValue.replace(".0","");
// HSSFCellStyle cellStyle = workbook.createCellStyle();
// HSSFDataFormat format= workbook.createDataFormat();
// cellStyle.setDataFormat(format.getFormat("#,##0.00"));
// cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
// cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell.setCellStyle(cellStyle);
cell.setCellValue(Double.parseDouble(textValue));
}else {
HSSFRichTextString richString = new HSSFRichTextString(
textValue);
// HSSFFont font3 = workbook.createFont(); zyu test
//font3.setColor(HSSFColor.BLUE_GREY.index);
// richString.applyFont(workbook.createFont());
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 {
// 清理资源
}
}
}
if(foottool!=null){
sheet.addMergedRegion(new Region(rowindex+1, (short) 0, rowindex+1, (short) (headers.length-1)));
rowindex+=2;
HSSFRow rowht = sheet.createRow(rowindex);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = rowht.createCell(i);
if(i<foottool.length){
HSSFRichTextString text = new HSSFRichTextString(foottool[i]);
cell.setCellValue(text);
}else{
sheet.addMergedRegion(new Region(rowindex, (short) i, rowindex, (short) (headers.length-1)));
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// public static void main(String[] args) {
// // 测试学生
// ExportExcelUtil<Student> ex = new ExportExcelUtil<Student>();
// String[] headers = { "学号", "姓名", "年龄", "性别", "出生日期" };
// List<Student> dataset = new ArrayList<Student>();
// dataset.add(new Student (10000001, "张三", 20, true, new Date()));
// dataset.add(new Student (20000002, "李四", 24, false, new Date()));
// dataset.add(new Student (30000003, "王五", 22, true, new Date()));
// // 测试图书
// ExportExcelUtil<Booktest> ex2 = new ExportExcelUtil<Booktest>();
// String[] headers2 = { "图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN",
// "图书出版社", "封面图片" };
// List<Booktest> dataset2 = new ArrayList<Booktest>();
// try {
// @SuppressWarnings("resource")
// BufferedInputStream bis = new BufferedInputStream(
// new FileInputStream("F://cc//01.gif"));//圖片
// byte[] buf = new byte[bis.available()];
// while ((bis.read(buf)) != -1) {
// //
// }
// dataset2.add(new Booktest(1, "jsp", "leno", 300.33f, " 1234567","清华出版社", buf));
// dataset2.add(new Booktest(2, "java编程思想", "brucl", 300.33f, " 1234567","阳光出版社", buf));
// dataset2.add(new Booktest(3, "DOM艺术", "lenotang", 300.33f, " 1234567","清华出版社", buf));
// dataset2.add(new Booktest(4, "c++经典", "leno", 400.33f, " 1234567","清华出版社", buf));
// dataset2.add(new Booktest(5, "c#入门", "leno", 300.33f, " 1234567","汤春秀出版社", buf));
//
// OutputStream out = new FileOutputStream("E://a.xls");
// OutputStream out2 = new FileOutputStream("E://b.xls");
// OutputStream out3 = new FileOutputStream("E://c.xls");
// OutputStream out4 = new FileOutputStream("E://d.xls");
// ex.exportExcel(headers, dataset, out);
// ex2.exportExcel(headers2, dataset2, out2);String test="測試";
// ex.exportExcel(test,headers, dataset, out3,2,null,null);
// String[] headerfoot = { "图书编号", "图书名称" };
// String[] foottool = { "图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN",
// "图书出版社", "封面图片" };
// ex.exportExcel(test,headers, dataset, out4,2,headerfoot,foottool);
// out.close();
// JOptionPane.showMessageDialog(null, "导出成功!");
// System.out.println("excel导出成功!");
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}