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
*/
@Override
protected 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>
模板图:
效果图: