public class POIUtil {
public static void main(String[] args) throws Exception {
List<User> list = new ArrayList<User>();
// list.add(new User("10001","张三",23,new Date()));
//创建hssfWorkbook
HSSFWorkbook workbook = new HSSFWorkbook();
if(list!=null || list.size()!=0){
Field[] fields = list.get(0).getClass().getDeclaredFields();
//创建工作簿
HSSFSheet sheet = workbook.createSheet("商品信息汇总");
//合并单元格
//param1:起始行 param2:结束行 param3:起始列 param4:结束列
sheet.addMergedRegion(new CellRangeAddress(0,0,0,(fields.length==0)?5:fields.length-1));
//修改行间距
sheet.setDefaultColumnWidth(10);
//创建标题
//指定标题所在的行
HSSFRow row = sheet.createRow(0);
//指定标题所在的列
HSSFCell cell = row.createCell(0);
//设定单元格样式
HSSFCellStyle cellStyle = workbook.createCellStyle();//获取样式对象
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置单元格居中对齐
HSSFFont font = workbook.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 14);
cellStyle.setFont(font);
cellStyle.setFillBackgroundColor((short)56);
cell.setCellValue("商品信息汇总");
cell.setCellStyle(cellStyle);
//创建副标题行
HSSFRow titleRow = sheet.createRow(1);
for (int i=0;i<fields.length;i++) {
HSSFCell titleCell = titleRow.createCell(i);
//titleCell.setCellStyle();//可设置样式
titleCell.setCellValue(fields[i].getName());//给当前列单元格设置小标题
}
//创建数据列
for (int i=0;i<list.size();i++) {
HSSFRow dataRow = sheet.createRow(i + 2);//开始创建数据的行位置
//遍历字段对象
for(int j=0;j<fields.length;j++){
HSSFCell dataCell = dataRow.createCell(j);
//dataCell.setCellStyle();//可给数据列设置样式
//通过反射获取对象的get方法
String getMethodName = "get"+fields[j].getName().substring(0,1).toUpperCase()+fields[j].getName().substring(1);
Method method = list.get(0).getClass().getDeclaredMethod(getMethodName, new Class[]{});
Object invoke = method.invoke(list.get(i), new Object[]{});
if(invoke.getClass() == Date.class){
dataCell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(invoke));
}else{
dataCell.setCellValue(invoke.toString());
}
}
}
}
//将exal输出到哪个文件夹中
FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\zhangkuan\\Desktop\\test.xls"));
workbook.write(fileOutputStream);
fileOutputStream.close();
workbook.close();
}
}