核心依賴
需求
導出多個表格,包含圖片,類似商品標簽
1.配置模板
創建一個xlsx的模板文件,配置如下
- 該模板進行遍歷了兩次,因為我想要導出的數據分為兩列展示,左右布局,一個循環實現不了,所以采用兩個循環奇偶遍歷展示
2.引入依賴
<dependency><groupId>org.jxls</groupId><artifactId>jxls</artifactId><version>2.12.0</version>
</dependency>
<dependency><groupId>org.jxls</groupId><artifactId>jxls-poi</artifactId><version>2.12.0</version>
</dependency>
3.創建測試類
package com.example;import org.example.SpringBootWsDemoApplication;
import org.example.domain.vo.ProductVO;
import org.junit.jupiter.api.Test;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.test.context.TestPropertySource;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;@SpringBootTest(classes = SpringBootWsDemoApplication.class)
@TestPropertySource(properties = {"app.template.path=classpath:/templates/jxl_temp_img2.xlsx"})
public class ExportImg2Test {@Value("${app.template.path}")private Resource templateResource;@Testpublic void test() throws IOException {List<ProductVO> batch = ProductVO.batchToJxls();// 創建上下文并設置數據Context context = new Context();context.putVar("products", batch);// 加載模板OutputStream os = new FileOutputStream("output_img.xlsx");// 獲取模板文件輸入流// InputStream templateStream = ExportTest.class.getResourceAsStream("templates/jxl_temp.xlsx");// JxlsHelper.getInstance().processTemplate(templateStream, os, context);// imageType圖片類型默認是PNG,支持:PNG, JPEG, EMF, WMF, PICT, DIB,模板中src是model中傳入的字節數組byte[]JxlsHelper instance = JxlsHelper.getInstance();instance.processTemplate(templateResource.getInputStream(), os, context);}}
4.效果圖
注意事項
-
模板文件放到
src/main/resources
下本地開發工具直接運行可以訪問,打包jar后也許訪問不到,這種情況如果出現了的話,要么就把模板文件放到服務器本地磁盤,通過文件路徑讀取,而不是從demo.jar!/BOOT-INF/classes!/templates/jxls_temp.xlsx -
導出需要的是一個圖片文件的byte數組
// InputStream imageInputStream = new FileInputStream("D:/qr.jpg");File file = ResourceUtils.getFile("classpath:static/img/qr.jpg");
// 使用工具方法把流轉成byte數組
byte[] imageBytes = Util.toByteArray(Files.newInputStream(file.toPath()));