java poi excel无法添加水印替代方法
生活随笔
收集整理的這篇文章主要介紹了
java poi excel无法添加水印替代方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
poi無法直接通過代碼生成水印效果,只能生成圖片以及背景圖。
提供一種可行辦法就是預留一份現成的帶有水印的excel模板,以模板創建workbook,再向其添加內容,這樣即可實現導出帶有水印的excel,需要注意的是poi版本不能太老,太老的不支持此操作。
代碼試例如下:
@WebServlet(name = "poiServlet", urlPatterns = "/public/poi") public class PoiCtrl extends HttpServlet {//excel模板路徑private final String poiModelPath = this.getClass().getClassLoader().getResource("/").getPath() + "poi_model.xls";/*** @description: poi水印* @date 17:12 2020/2/10* @param req* @param resp* @exception java.rmi.ServerException* @exception IOException* @return void*/@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {try (InputStream inputStream = new FileInputStream( new File(poiModelPath) )){HSSFWorkbook workbook = new HSSFWorkbook(inputStream);Font baseFont = workbook.createFont();baseFont.setBold(true);baseFont.setFontHeightInPoints((short) 10);CellStyle baseStyle = workbook.createCellStyle();baseStyle.setAlignment(HorizontalAlignment.CENTER);baseStyle.setVerticalAlignment(VerticalAlignment.CENTER);Sheet sheet = workbook.getSheetAt(0);for (int i = 0; i < 10; i++) {sheet.setColumnWidth(i, 20 * 256);//設置每一列的寬度}sheet.createFreezePane(0,1, 0, 1);//凍結首行for (int i = 0; i < 20; i++) {Row row = sheet.createRow(i);row.setHeightInPoints(34f);for (int j = 0; j < 10; j++) {Cell cell = row.createCell(j);cell.setCellValue( i + ":" + j );cell.setCellStyle(baseStyle);}}try (OutputStream outputStream = resp.getOutputStream()){resp.reset();resp.setContentType("application/msExcel");resp.setHeader("Content-Disposition", "attachment;filename=price.xls");workbook.write(outputStream);}}} }maven:
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.0</version> </dependency>模板圖:?
效果圖:
?
總結
以上是生活随笔為你收集整理的java poi excel无法添加水印替代方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端如何让倒计时更准确
- 下一篇: java按位取反“~“运算符,负数右移