poi到处数据 使用反射机制 动态取字段数据

来源:互联网 发布:想开淘宝没有货 编辑:程序博客网 时间:2024/06/05 11:22

package demo;


import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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.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.ss.formula.functions.T;


public class ExcelOpt {


public HSSFWorkbook writeExcel(String title, String[] headers,
String[] fields, Collection<T> dataSet, OutputStream out,
String pattern) {


HSSFWorkbook workbook = new HSSFWorkbook();


DecimalFormat df = new DecimalFormat("0.0000");


HSSFSheet sheet = workbook.createSheet();
sheet.setDefaultColumnWidth(20);


// 样式标题
HSSFCellStyle headStyle = workbook.createCellStyle();
// 数据样式
HSSFCellStyle dataStyle = workbook.createCellStyle();


HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(headStyle);
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();
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(dataStyle);
String fieldName = fields[i];
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
Class tcls = 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 if (value instanceof Double) {
cell.setCellValue(df.format(value));
} else {
textValue = valueToString(value);
}


if (textValue != null) {
Pattern p = Pattern.compile("^\\d+(\\.\\d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches() && !(value instanceof String)) {
cell.setCellValue(Double.parseDouble(textValue));
} else {
cell.setCellValue(new HSSFRichTextString(textValue));
}
}
} 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();
}
}
}


return workbook;


}


public static final String valueToString(Object obj) {
return obj == null ? "" : obj.toString();
}


}

0 0