如下:
@Override
public InputStream expUseTemplate() {
//Excel模板文件key
String fileKey = "7qIYXt8YH1bYN7e9nEo";
// 校验模板是否存在
FileBO fileBO = documentBusService.readFile(fileKey);
// 缓存为临时文件
String PACKAGE_TEMP_FILE_PATH = System.getProperty("jeplus.webapp") + "/excel_temp/%s.%s";
String tempFilePath = String.format(PACKAGE_TEMP_FILE_PATH, System.currentTimeMillis(), fileBO.getSuffix());
FileUtil.writeFromStream(fileBO.getFile(), tempFilePath);
File tempFile = new File(tempFilePath);
// 开始位置
int sheetIndex = 0;
// 创建excel操作对象
Workbook book = WorkbookUtil.createBook(tempFile);
Sheet sheet = book.getSheetAt(sheetIndex);
//根据文件id获取图片流
fileBO = documentBusService.previewFile("4WnlI02EWt1UrjcD8YS", SecurityUserHolder.getCurrentUser().getUserId());
int pictureIdx = 0;
try {
pictureIdx = book.addPicture(IOUtils.toByteArray(fileBO.getFile()), Workbook.PICTURE_TYPE_JPEG);
} catch (IOException e) {
e.printStackTrace();
}
Drawing drawing = sheet.createDrawingPatriarch();
CreationHelper helper = book.getCreationHelper();
//设置大小和位置
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(3);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
//最终插入
pict.resize();
try {
// 写出数据到流
ByteArrayOutputStream out = new ByteArrayOutputStream();
book.write(out);
out.flush();
ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toByteArray());
IoUtil.close(out);
IoUtil.close(book);
return inputStream;
} catch (Exception e) {
e.printStackTrace();
}
return FileUtil.getInputStream(tempFile);
}