若您正在使用easypoi進行excel導出的話,希望這篇文章能幫到您。
本文主要是使用easypoi通過模版的形式導出圖檔。
若需要導出多sheet得話,非模版形式,可以參考我的文章EasyPOI->非模版形式導出Excel(多Sheet)。
模版形式的多sheet導出可參考:EasyPOI->模版形式導出Excel(多Sheet)
模版導出可參考我的文章Easypoi導出excel。
POM依賴如下:
<!-- easypoi -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
導出圖檔代碼如下:
@Controller
@RequestMapping(value = "exportexcel")
public class ExportExcelTest {
@RequestMapping(value="exportexceltest")
@ResponseBody
public String exportExcelTest(HttpServletResponse response){
// 擷取workbook對象
Workbook workbook = exportPicture() ;
// 判斷資料
if(workbook == null) {
return "fail";
}
// 設定excel的檔案名稱
String excelName = "測試excel" ;
// 重置響應對象
response.reset();
// 目前日期,用于導出檔案名稱
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dateStr = "["+excelName+"-"+sdf.format(new Date())+"]";
// 指定下載下傳的檔案名--設定響應頭
response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xls");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 寫出資料輸出流到頁面
try {
OutputStream output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
workbook.write(bufferedOutPut);
bufferedOutPut.flush();
bufferedOutPut.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
public Workbook exportPicture() {
TemplateExportParams params = new TemplateExportParams(
"d:/項目測試檔案夾/easyPoiExportPicture.xlsx", true);
//
Map<String, Object> map = new HashMap<String, Object>();
// 資料清單
List<Map<String, Object>> pictureList = new ArrayList<Map<String, Object>>() ;
// 建立資料對象
Map<String, Object> temp = new HashMap<String, Object>();
// 建立圖檔
ImageEntity image = new ImageEntity();
image.setHeight(1000);
image.setWidth(2500);
image.setUrl("static/images/fu.jpg");
//
temp.put("name","福字") ;
temp.put("image", image);
//
pictureList.add(temp);
// 建立資料對象
Map<String, Object> temp1 = new HashMap<String, Object>();
// 建立圖檔
ImageEntity image1 = new ImageEntity();
image1.setHeight(2000);
image1.setWidth(5000);
image1.setUrl("static/images/tree.jpg");
//
temp1.put("name","樹") ;
temp1.put("image", image1);
//
pictureList.add(temp1);
//
map.put("i" , pictureList);
//
Workbook book = ExcelExportUtil.exportExcel(params, map);
//
return book ;
}
}
模版示例:

導出後結果:
注意:圖檔的寬高需要通過ImageEntity對象的width和height屬性指定,且每列圖檔的寬高需相同。
其他相關使用請參考原文章:http://easypoi.mydoc.io/#text_217673
如您有其他問題,希望可以通過留言得形式及時交流,有書寫錯誤和可優化的地方也希望及時提出,感謝。