java - 设置 Excel 工作表背景图片
问题描述
我想问你是否有任何方法可以使用 Apache Excel POI 将图像设置为工作表背景?我只能找到如何设置单元格的背景颜色。我想要使用Excel -> Page Layout -> Background获得的相同功能。
先感谢您。
解决方案
答案取决于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 记录一样复杂,需要很长时间 - 有没有更好的方法?.
推荐阅读
- azure - azure 角色:所有者、全局管理员 AAD
- ms-access - 从多个字段查询/关系到相关表/查询中的单个字段
- java - 如何获取我的 java 应用程序所需的传递依赖项列表?
- ios - 无法让社交媒体提要在 firebase 和 swift 中工作
- python - 图像在调整大小的最后一步变为空
- c - 我需要一个函数来初始化这个数组
- java - Android:从文本文件读取 - 完成异常打开失败:ENOENT(没有这样的文件或目录)
- sql - 如何设计用于存储目的地的表格或集合?
- c - 为什么在程序下面运行时,void print_size(int a[]) 函数中 sizeof(a) 的输出是 8,而 int main() 函数中 sizeof(a) 是 12?
- c++ - GLFWwindow * window 是否仍然指向有效的 glfw 对象?