我想问一下是否有任何方法可以使用Apache Excel POI将图像设置为工作表背景?我只能找到如何设置单元格的背景色。我希望您使用 Excel->页面布局->背景获得相同的功能。
谢谢。
答案 0 :(得分:3)
答案取决于Excel
文件的类型。
对于Office Open XML
格式*.xlsx
,它很简单:
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.util.IOUtils;
public class CreateExcelXSSFSheetBackgroundPicture {
public static void main(String[] args) throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream out = new FileOutputStream("CreateExcelXSSFSheetBackgroundPicture.xlsx")) {
XSSFSheet sheet = workbook.createSheet("Sheet1");
//add picture data to this workbook.
FileInputStream is = new FileInputStream("dummy.png");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
is.close();
//add relation from sheet to the picture data
String rID = sheet.addRelation(null, XSSFRelation.IMAGES, workbook.getAllPictures().get(pictureIdx))
.getRelationship().getId();
//set background picture to sheet
sheet.getCTWorksheet().addNewPicture().setId(rID);
workbook.write(out);
}
}
}
对于二进制BIFF
格式*.xls
,它与Using java.awt.image.BufferedImage for creating BIFF8 BITMAP record takes much time - Is there any better approach?一样复杂。
答案 1 :(得分:0)
如果你使用 poi 5. maven repo 应该。 它仅适用于 xlsx。
<poi.version>5.0.0</poi.version>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-full</artifactId>
<version>${poi.version}</version>
</dependency>
spring boot 和使用 lombok
public void addWatermark() throws IOException {
val workbook = WorkbookFactory.create(this.inputStream);
XSSFWorkbook wb =(XSSFWorkbook) workbook;
// get an image input stream from classpath
ClassPathResource classPathResource = new ClassPathResource("bub.png");
InputStream inputStream = classPathResource.getInputStream();
int pictureIdx = workbook.addPicture(IOUtils.toByteArray(inputStream), Workbook.PICTURE_TYPE_PNG);
inputStream.close();
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
XSSFSheet sheet = wb.getSheetAt(i);
String rID = sheet.addRelation(null, XSSFRelation.IMAGES,wb
.getAllPictures().get(pictureIdx)).getRelationship().getId();
sheet.getCTWorksheet().addNewPicture().setId(rID);
}
}