java excel表格加水印
时间: 2023-08-25 14:07:44 浏览: 101
可以使用 Apache POI 库来操作 Excel 表格并添加水印,具体步骤如下:
1. 导入 Apache POI 库。
2. 创建一个 Excel 文件对象并读取要添加水印的 Excel 表格。
```
FileInputStream fis = new FileInputStream("test.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
```
3. 获取当前工作表对象。
```
XSSFSheet sheet = workbook.getSheetAt(0);
```
4. 创建一个 Drawing 对象并将其添加到当前工作表中。
```
XSSFDrawing drawing = sheet.createDrawingPatriarch();
```
5. 创建一个文本框并设置其位置、大小、内容和样式。
```
XSSFSimpleShape shape = drawing.createSimpleShape(new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 1, 1));
shape.setShapeType(ShapeTypes.TEXT_BOX);
shape.setFillColor(255, 255, 255);
shape.setLineStyle(0);
shape.setLineStyleColor(255, 255, 255);
shape.setLineWidth(0);
shape.setNoFill(true);
shape.setAnchor(new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 10, 10));
shape.setText("水印内容");
XSSFRichTextString rts = shape.getRichText();
XSSFFont font = workbook.createFont();
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
font.setItalic(true);
font.setFontHeightInPoints((short) 20);
rts.applyFont(font);
```
6. 保存 Excel 文件。
```
FileOutputStream fos = new FileOutputStream("test.xlsx");
workbook.write(fos);
workbook.close();
fis.close();
fos.close();
```
完整代码如下:
```
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
public class AddWatermarkToExcel {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("test.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFSimpleShape shape = drawing.createSimpleShape(new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 1, 1));
shape.setShapeType(ShapeTypes.TEXT_BOX);
shape.setFillColor(255, 255, 255);
shape.setLineStyle(0);
shape.setLineStyleColor(255, 255, 255);
shape.setLineWidth(0);
shape.setNoFill(true);
shape.setAnchor(new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 10, 10));
shape.setText("水印内容");
XSSFRichTextString rts = shape.getRichText();
XSSFFont font = workbook.createFont();
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
font.setItalic(true);
font.setFontHeightInPoints((short) 20);
rts.applyFont(font);
FileOutputStream fos = new FileOutputStream("test.xlsx");
workbook.write(fos);
workbook.close();
fis.close();
fos.close();
}
}
```
阅读全文
相关推荐


















