首页 > 解决方案 > 设置 Excel 工作表背景图片

问题描述

我想问你是否有任何方法可以使用 Apache Excel POI 将图像设置为工作表背景?我只能找到如何设置单元格的背景颜色。我想要使​​用Excel -> Page Layout -> Background获得的相同功能。

先感谢您。

标签: javaexcelapache-poi

解决方案


答案取决于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);

  }

 }
}

此代码需要FAQ N10025ooxml-schemas-1.4.jar中提到的所有模式的完整jar apache poi 4.1.1(旧版本的较低版本)。

对于二进制BIFF格式*.xls,它与使用 java.awt.image.BufferedImage 来创建 BIFF8 BITMAP 记录一样复杂,需要很长时间 - 有没有更好的方法?.


推荐阅读