controller层使用 poi 导出excel 并下载
1 import org.apache.poi.ss.usermodel.BorderStyle; 2 import org.apache.poi.ss.usermodel.CellStyle; 3 import org.apache.poi.ss.usermodel.Font; 4 import org.apache.poi.ss.usermodel.IndexedColors; 5 import org.apache.poi.ss.util.CellRangeAddress; 6 import org.apache.poi.hssf.usermodel.HSSFCell; 7 import org.apache.poi.hssf.usermodel.HSSFRow; 8 import org.apache.poi.hssf.usermodel.HSSFSheet; 9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
Calendar date = Calendar.getInstance(); String strYear = String.valueOf(date.get(Calendar.YEAR)); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String time = sdf.format(new Date()); String sheetName = "散埋乱葬报表"; //sheetName String fileName = strYear + "散埋乱葬整治情况汇总表" + time + ".xls"; //设置要导出的文件的名字 HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(sheetName); //创建table工作薄 HSSFRow row; HSSFCell cell; row = sheet.createRow(0); //创建第一行 cell = row.createCell(0); //第一行第一个单元格 cell.setCellValue(head); //赋值 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9)); //合并单元格 起始行,结束行,起始列,结束列 //被合并的单元格 也要创建
response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); response.flushBuffer(); wb.write(response.getOutputStream());
CellStyle cellStyle=wb.createCellStyle(); //创建格式
cellStyle.setWrapText(true);//自动换行
cellStyle.setBorderBottom(BorderStyle.THIN);//设置底部边框
cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());//设置底部边框颜色
cellStyle.setBorderLeft(BorderStyle.THIN);//设置左部边框
cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());//设置左部边框颜色
cellStyle.setBorderRight(BorderStyle.THIN);//设置右部边框
cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());//设置右部边框颜色
cellStyle.setBorderTop(BorderStyle.THIN);//设置顶部边框
cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());//设置顶部边框颜色
sheet.setColumnWidth(0,9*256); //设置列宽
row.setHeightInPoints(40);//设置行高
cell.setCellStyle(cellstyle); //使用格式
Font font2=wb.createFont();
font2.setFontHeightInPoints((short)11);
font2.setFontName("宋体");
cellStyle.setFont(font2); //设置字体
原文:https://www.cnblogs.com/kaokao/p/11951599.html