/** * @Des 创建2007版Excel文件 * @Author hujin * @date 2017/2/16 13:21 */ public static void create2007Excel(String[] title, List<Object> listContent, HttpServletResponse response) throws Exception { XSSFWorkbook workBook = new XSSFWorkbook();// 创建 一个excel文档对象 XSSFSheet sheet = workBook.createSheet();// 创建一个工作薄对象 XSSFCellStyle style = workBook.createCellStyle();// 创建样式对象 // 设置字体 XSSFFont font = workBook.createFont();// 创建字体对象 font.setFontHeightInPoints((short) 15);// 设置字体大小 font.setFontName("黑体");// 设置为黑体字 style.setFont(font);// 将字体加入到样式对象 // 设置对齐方式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 //设置标题 XSSFRow titleRow = sheet.createRow(0);// 创建一个行对象 for (int i = 0; i < title.length; i++) { XSSFCell cell = titleRow.createCell(i);// 创建单元格 cell.setCellValue(title[i]);// 写入当前日期 cell.setCellStyle(style);// 应用样式对象 } int i = 1; Field[] fields = null; for (Object obj : listContent) { XSSFRow row = sheet.createRow(i);// 创建一个行对象 row.setHeightInPoints(23);// 设置行高23像素 //获取属性反射 fields = obj.getClass().getDeclaredFields(); int j = 0; for (Field v : fields) { v.setAccessible(true); //获取属性 Object va = v.get(obj); if (va == null) { va = ""; } XSSFCell cell = row.createCell(j);// 创建单元格 cell.setCellValue(va.toString());// 写入当前日期 cell.setCellStyle(style);// 应用样式对象 j++; } i++; } String fileName = "列表"+"-"+DateUtil.dateToDateString(new Date(),DateUtil.yyyy_MM_dd_HH_mm_ss_CN); fileName = URLEncoder.encode(fileName, "UTF-8"); // 文件输出流 response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.concat(".").concat("xlsx").getBytes())); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); workBook.write(toClient);// 将文档对象写入文件输出流 toClient.flush(); toClient.close(); }
web列表导出excel
最新推荐文章于 2022-08-05 10:58:57 发布