FileOutputStream fos = null;
File excelFile = new File("D:/s.xls");
try {
excelFile.delete();
//判断文件路径是否存在
if (!excelFile.exists()) {excelFile.createNewFile();
}
fos = new FileOutputStream(excelFile);
// 创建excel和sheet
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet();
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short) 18);
font.setBoldweight((short) 10);
// 创建cellStyle
HSSFCellStyle style = wb.createCellStyle();
style.setFont(font);
// 带上下左右边界、居中、自动换行
HSSFCellStyle styleBorderC = wb.createCellStyle();
styleBorderC.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
styleBorderC.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
styleBorderC.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
styleBorderC.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
styleBorderC.setAlignment(HSSFCellStyle.ALIGN_CENTER);
styleBorderC.setWrapText(true);
// 带上下左右边界、居左、自动换行
HSSFCellStyle styleBorderL = wb.createCellStyle();
styleBorderL.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
styleBorderL.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
styleBorderL.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
styleBorderL.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
styleBorderL.setAlignment(HSSFCellStyle.ALIGN_LEFT);
styleBorderL.setWrapText(true);
// 带上下左右边界、居右、自动换行
HSSFCellStyle styleBorderR = wb.createCellStyle();
styleBorderR.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
styleBorderR.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
styleBorderR.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
styleBorderR.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
styleBorderR.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
styleBorderR.setWrapText(true);
// 设置sheet名
wb.setSheetName(0, "sheet1");
HSSFRow row = null;
// 设置报表表头
// 表第一行
// 表名
HSSFRow row0 = s.createRow(0);
HSSFCell cell01 = row0.createCell(2);
cell01.setCellType(HSSFCell.CELL_TYPE_STRING);
cell01.setCellStyle(style);
cell01.setCellValue("创建excel");
// 表第二行
HSSFRow row1 = s.createRow(1);
HSSFCell cell10 = row1.createCell( 0);
cell10.setCellType(HSSFCell.CELL_TYPE_STRING);
cell10.setCellValue("欢迎您");
// 当前行数
row = s.createRow(3);//索引值是第四行
// 填写报表数据
for(int i=0;i<3;i++){
HSSFCell cell = null;
cell = row.createCell(i);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(i+1);
}
wb.write(fos);
fos.close();
} catch (IOException e) {
System.out.println(e);
}finally {
//excelFile.delete();对创建的文件进行删除
}
}