@RequestMapping(value = "/outURL", method = RequestMethod.GET) @ApiOperation(value = "导出超链接") public void outURL(HttpServletResponse response) throws IOException { //使用模板导出 Resource resource=new ClassPathResource("file/test.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(resource.getInputStream()); XSSFSheet mainSheet = workbook.getSheetAt(0); //统一设置默认列宽,width为字符个数 mainSheet.setDefaultColumnWidth(20); //模板数据行 样式 Row styleRow = mainSheet.getRow(2); CellStyle[] cellStyles=new CellStyle[styleRow.getLastCellNum()]; for (int c=0;c<styleRow.getLastCellNum();c++){ CellStyle cellStyle = styleRow.getCell(c).getCellStyle(); cellStyle.setWrapText(true); //设置自动换行 cellStyles[c]=cellStyle; } //超链接 单元格样式 XSSFCellStyle style = workbook.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); //垂直居中 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //设置边框 style.setBorderTop(CellStyle.BORDER_THIN); style.setBorderRight(CellStyle.BORDER_THIN); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderLeft(CellStyle.BORDER_THIN); //设置字体 XSSFFont font = workbook.createFont(); font.setUnderline(XSSFFont.U_DOUBLE); font.setColor(IndexedColors.BLUE.getIndex()); font.setFontName("宋体"); //字体 font.setFontHeightInPoints((short) 12); //字体大小 style.setFont(font); style.setWrapText(true); //设置自动换行 //第一行 数据 //序号 XSSFRow row1=mainSheet.createRow(2); XSSFCell cell = row1.createCell(0); cell.setCellValue("1"); cell.setCellStyle(cellStyles[0]); //使用模板样式 //名称 XSSFCell cell2 = row1.createCell(1); cell2.setCellValue("百度"); cell2.setCellStyle(cellStyles[1]); //编号 XSSFCell cell3 = row1.createCell(2); cell3.setCellValue("baidu"); cell3.setCellStyle(cellStyles[2]); //网址超链接 XSSFCell cell4 = row1.createCell(3); CreationHelper createHelper = workbook.getCreationHelper(); XSSFHyperlink link = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL); link.setAddress("http://www.baidu.com"); //地址需要加 http cell4.setHyperlink(link); cell4.setCellValue("查看"); cell4.setCellStyle(style); //使用超链接样式 //第二行数据 //序号 XSSFRow row2=mainSheet.createRow(3); XSSFCell cell22 = row2.createCell(0); cell22.setCellValue("2"); cell22.setCellStyle(cellStyles[0]); //名称 XSSFCell cell23 = row2.createCell(1); cell23.setCellValue("问题排查"); cell23.setCellStyle(cellStyles[1]); //编号 XSSFCell cell33 = row2.createCell(2); cell33.setCellValue("problem"); cell33.setCellStyle(cellStyles[2]); //文件超链接 XSSFCell cell34 = row2.createCell(3); link = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_FILE); link.setAddress("f:/排查问题.txt"); //路径要正确 cell34.setHyperlink(link); cell34.setCellValue("查看"); cell34.setCellStyle(style); String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); fileName = URLEncoder.encode(fileName, "UTF8"); response.setContentType("application/vnd.ms-excel;chartset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename="+fileName + ".xlsx"); workbook.write(response.getOutputStream()); }
poi导出excel设置超链接、字体样式、边框等
最新推荐文章于 2021-12-16 10:59:09 发布