1.代码
/**
* 完成功能:输出Excel
* @param path 即将生成Excel的所在包路径
* @param fileName Excel名称
* @param fileType Excel类型(xlsx/xls)
* @param list 填充到Excel的数据
* @param titleRow Excel的题头数组
* @return excelPath 生成Excel的路径
* @throws IOException
*/
public static String writerPro(String path, String fileName, String fileType, List<PhfinancialPro> list,
String[] titleRow) throws IOException {
Workbook wb = null;
String excelPath = path+fileName+"."+fileType;
File file = new File(excelPath);
Sheet sheet =null;
//创建工作文档对象
if (!file.exists()) {
if (fileType.equals("xls")) {
wb = new HSSFWorkbook();
} else if(fileType.equals("xlsx")) {
wb = new XSSFWorkbook();
} else {
System.out.println("Error");
}
} else {
if (fileType.equals("xls")) {
wb = new HSSFWorkbook();
} else if(fileType.equals("xlsx")) {
wb = new XSSFWorkbook();
} else {
System.out.println("Error");
}
}
//创建sheet对象
if (sheet==null) {
sheet = (Sheet) wb.createSheet("sheet1");
}
//添加表头
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
row.setHeight((short) 540);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
String dateString = formatter.format(new Date());
cell.setCellValue("普惠金融风控报告专业版("+dateString+")"); //创建第一行
CellStyle style = wb.createCellStyle(); // 样式对象
// 设置单元格的背景颜色为淡蓝色
style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直
style.setAlignment(CellStyle.ALIGN_CENTER);// 水平
style.setWrapText(true);// 指定当单元格内容显示不下时自动换行
cell.setCellStyle(style); // 样式,居中
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setFontHeight((short) 280);
style.setFont(font);
// 单元格合并
// 四个参数分别是:起始行,起始列,结束行,结束列
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
sheet.autoSizeColumn(5200);
row = sheet.createRow(1); //创建第二行
for(int i = 0;i < titleRow.length;i++){
cell = row.createCell(i);
cell.setCellValue(titleRow[i]);
cell.setCellStyle(style); // 样式,居中
sheet.setColumnWidth(i, 20 * 256);
}
row.setHeight((short) 800);
//循环写入行数据
for (int i = 0; i < list.size(); i++) {
row = (Row) sheet.createRow(i+2);
row.setHeight((short) 500);
row.createCell(0).setCellValue(( list.get(i)).getNam());
row.createCell(1).setCellValue(( list.get(i)).getIdcar());
row.createCell(2).setCellValue(( list.get(i)).getPhon());
row.createCell(3).setCellValue(( list.get(i)).getFailNum());
row.createCell(4).setCellValue(( list.get(i)).getFailOrg());
row.createCell(5).setCellValue(( list.get(i)).getFailTim());
row.createCell(6).setCellValue(( list.get(i)).getOveNum());
row.createCell(7).setCellValue(( list.get(i)).getOveNum());
row.createCell(8).setCellValue(( list.get(i)).getOveO());
row.createCell(9).setCellValue(( list.get(i)).getOveM());
}
//创建文件流
OutputStream stream = new FileOutputStream(excelPath);
//写入数据
wb.write(stream);
//关闭文件流
stream.close();
return excelPath;
}
2.jar包
xmlbeans-2.6.0.jar;
poi-3.8-20120326.jar;
poi-ooxml-3.8-20120326.jar;
poi-ooxml-schemas-3.8-20120326.jar;
dom4j.jar