Set Excel sheet background image

久未见 提交于 2020-12-06 06:41:38

问题


I would like to ask you if there is any way setting image as sheet background using Apache Excel POI? I was only able to find how to set background color of the cell. I want same functionality you get using Excel -> Page Layout -> Background.

Thank you in advance.


回答1:


The answer depends on the type of the Excel file.

For Office Open XML format *.xlsx it is as simple as:

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);

  }

 }
}

This code needs the full jar of all of the schemas ooxml-schemas-1.4.jar for apache poi 4.1.1 (lower versions for older releases) as mentioned in FAQ N10025.

For binary BIFF format *.xls it is as complicated as Using java.awt.image.BufferedImage for creating BIFF8 BITMAP record takes much time - Is there any better approach?.



来源:https://stackoverflow.com/questions/52835900/set-excel-sheet-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!