easypoi的封裝是非常好的,用起來很簡單。
官方教程地址:http://easypoi.mydoc.io/
但是在使用模板導出圖片到合併單元格時出問題了,官網找了好幾遍沒找到方案。
其實官方早就實現了只是沒有直接的文檔說明。解決辦法:
走起:
先上圖片:
1、模板
2、導出效果
3、文件存放位置
4、代碼實現
坑就在這裏,官網裏有這個模板導出圖片的例子,但是是導出到單個單元格。沒說合並單元格的情況下怎麼導出。所以我在模板裏合併了單元格,再導出的圖片,結果圖片只填充第一個單元格,並沒有填充滿整個合併後的單元格。然後就設置寬和高,結果只是撐大了第一個單元格。網上都查遍了也沒有解決方案。最後自己仔細看了看ImageEntity這個類,測試後發現,通過ImageEntity再去合併單元格就ok了。在此呈上解決方案。
import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ExcelTest {
public static void main(String[] args) {
//第二個參數true是爲了開啓多sheet掃描,就是同一個xls文件中有多個工作表的時候。
// false則只填充一個sheet。我這裏只有一個sheet可以爲false。也可以爲true
TemplateExportParams params = new TemplateExportParams("E:\\easypoi\\temp.xlsx", true);
//創建map存放需要替換的內容
Map<String,Object> map = new HashMap<>();
map.put("name","groot");//添加姓名
//下邊開始添加圖片。有幾個注意點。
ImageEntity image = new ImageEntity();
//#1、大小盡量不要在這裏設置、在模板裏調整好大小更好。不設置圖片大小就會直接填充滿模板裏的單元格。
// image.setHeight(200);
// image.setWidth(500);
//#2、這裏是設置合併單元格,但是千萬不要再模板你提前合併單元格。合併了這裏會報錯。行合併多少個格子在這裏設置。
image.setRowspan(3);//向下合併三行
image.setColspan(2);//向右合併兩列
//添加圖片
image.setUrl("E:\\easypoi\\1.jpg");
map.put("desktop",image);//放入map
//放入desktop圖片
ImageEntity image2 = new ImageEntity();
// image.setHeight(200);
// image.setWidth(500);
image2.setRowspan(3);
image2.setUrl("E:\\easypoi\\2.png");
map.put("qrcode",image2);
//數據載入,生成excel文件
Workbook book = ExcelExportUtil.exportExcel(params, map);
//創建保存路徑、這不可以省略、如果路徑存在了可以不用創建。這裏是防止路徑不存在的
File savefile = new File("E:\\easypoi\\");
if (!savefile.exists()) {
savefile.mkdirs();
}
try {
//設置導出文件名、創建輸出流
FileOutputStream fos = new FileOutputStream("E:\\easypoi\\excel.xlsx");
//導出excel文件
book.write(fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5、pom配置依賴(貌似所有的都在這了,這個功能只需要使用easypoi-base即可)
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-base -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-annotation -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-web -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi</artifactId>
<version>4.1.2</version>
<type>pom</type>
</dependency>