简单poi创建execl

时间:2023-02-05 03:12:42
Workbook workbook = new HSSFWorkbook();// 创建一个Excel文件
Workbook workbook = new XSSFWorkbook();// 创建一个Excel文件
Sheet sheet = workbook.createSheet();// 创建一个Excel的Sheet
sheet.createFreezePane(1, 5);// 绿色的线条,死线
sheet.setColumnWidth(0, 2000);// 设置列宽
// 字体样式
Font columnHeadFont = workbook.createFont();
columnHeadFont.setFontName("宋体");
columnHeadFont.setFontHeightInPoints((short) 10);//字体大小
columnHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字体颜色
// 列头的样式
CellStyle columnHeadStyle = workbook.createCellStyle();
columnHeadStyle.setFont(columnHeadFont);//加入columnHeadFont字体样式
columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
columnHeadStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
columnHeadStyle.setLocked(true);
columnHeadStyle.setWrapText(true);
columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);// 左边框的颜色
columnHeadStyle.setBorderLeft((short) 1);// 边框的大小
columnHeadStyle.setRightBorderColor(HSSFColor.BLACK.index);// 右边框的颜色
columnHeadStyle.setBorderRight((short) 1);// 边框的大小
columnHeadStyle.setTopBorderColor(HSSFColor.BLACK.index);// 上边框的颜色
columnHeadStyle.setBorderTop((short) 1);// 边框的大小
columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index);// 下边框的颜色
columnHeadStyle.setBorderBottom((short) 1);// 边框的大小
columnHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体
columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色
// 设置单元格的背景颜色(单元格的样式会覆盖列或行的样式)
columnHeadStyle.setFillForegroundColor(HSSFColor.WHITE.index);
// 创建第一行
Row row0 = sheet.createRow(0);
// 设置行高
row0.setHeight((short) 900);
// 创建第一列
Cell cell0 = row0.createCell(0);
//合并第0行到第0行,0列到4列
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4)); //创建第四行
Row row3 = sheet.createRow(4);
row3.setHeight((short) 400);//行高
cell = row3.createCell(0);//第0列
cell.setCellValue(new HSSFRichTextString("序号"));
cell.setCellStyle(columnHeadStyle);//加入columnHeadStyle样式

输出:

1.将文件写入磁盘

        FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream("文件路径+文件名");
workBook.write(fileOut);
fileOut.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e1) {
throw e1;
}
}
}

2.下载文件:

     Workbook wb=new Workbook ();
OutputStream output=null;
try{
output=response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename="+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+".xlsx");
response.setContentType("application/msexcel");
wb.write(output);
}
catch (Exception e){
e.printStackTrace();
} finally {
try {
if(output != null){
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

                                                              ---朱星翰