Java中Easyexcel?實現(xiàn)批量插入圖片功能
各位今天給大家分享Easyexcel 實現(xiàn)批量插入圖片的問題,代碼如下所示:
1 Maven依賴
<!--hutool工具包--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.5.1</version> </dependency> <!--easyexcel文檔處理工具--> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.8</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
2 PictureModel
圖片信息。
package com.xudongbase.easyexcel.model; import com.xudongbase.easyexcel.model.builder.PictureModelBuilder; import com.xudongbase.easyexcel.model.common.SheetRangeModel; import lombok.Getter; /** * 圖片信息 * * @author xudongmaster */ @Getter public class PictureModel extends SheetRangeModel { /** * 圖片數(shù)據(jù) */ private byte[] pictureBytes; * 圖片類型 private Integer pictureType; public PictureModel(PictureModelBuilder builder) { this.sheetName = builder.getSheetName(); this.startRowIndex = builder.getStartRowIndex(); this.endRowIndex = builder.getEndRowIndex(); this.startColumnIndex = builder.getStartColumnIndex(); this.endColumnIndex = builder.getEndColumnIndex(); this.pictureBytes = builder.getPictureBytes(); this.pictureType = builder.getPictureType(); } * 生成圖片信息 * * @param sheetName sheet頁名稱 * @param startRowIndex 開始行號 * @param endRowIndex 結(jié)束行號 * @param startColumnIndex 開始列號 * @param endColumnIndex 結(jié)束列號 * @param pictureBytes 圖片數(shù)據(jù) * @return public static PictureModel createPictureModel(String sheetName, int startRowIndex, int endRowIndex, int startColumnIndex, int endColumnIndex , byte[] pictureBytes) { return createPictureModel(sheetName, startRowIndex, endRowIndex, startColumnIndex, endColumnIndex, pictureBytes, null); * @param pictureType 圖片類型 , byte[] pictureBytes, Integer pictureType) { return new PictureModelBuilder(sheetName, startRowIndex, endRowIndex, startColumnIndex, endColumnIndex, pictureBytes) //圖片類型 .pictureType(pictureType) .build(); }
3CustomPictureHandler
自定義圖片處理器。
package com.xudongbase.easyexcel.handler; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.excel.write.handler.SheetWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; import com.xudongbase.common.poi.util.POIExcelUtil; import com.xudongbase.easyexcel.model.PictureModel; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * 自定義圖片處理器 * * @author xudongmaster */ public class CustomPictureHandler implements SheetWriteHandler { /** * sheet頁名稱列表 */ private List<String> sheetNameList; * 圖片信息 private List<PictureModel> pictureList = new ArrayList<>(); public CustomPictureHandler(List<PictureModel> pictureList) { if (CollUtil.isEmpty(pictureList)) { return; } this.pictureList = pictureList.stream().filter(x -> StrUtil.isNotBlank(x.getSheetName()) && x.getPictureBytes() != null && x.getPictureBytes().length > 0) .collect(Collectors.toList()); sheetNameList = this.pictureList.stream().map(x -> x.getSheetName()).distinct().collect(Collectors.toList()); } @Override public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) { * sheet頁創(chuàng)建之后調(diào)用 * * @param writeWorkbookHolder * @param writeSheetHolder public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) { Sheet sheet = writeSheetHolder.getSheet(); //不需要添加圖片,或者當前sheet頁不需要添加圖片 if (CollUtil.isEmpty(pictureList) || sheetNameList.contains(sheet.getSheetName()) == false) { //獲取當前sheet的圖片 List<PictureModel> sheetPictureList = pictureList.stream().filter(x -> StrUtil.equals(x.getSheetName(), sheet.getSheetName()) ).collect(Collectors.toList()); //當前sheet頁不需要圖片 if (CollUtil.isEmpty(sheetPictureList)) { for (PictureModel pictureModel : sheetPictureList) { //圖片數(shù)據(jù) byte[] pictureBytes = pictureModel.getPictureBytes(); //插入圖片 POIExcelUtil.insertImg(writeWorkbookHolder.getWorkbook(), sheet, pictureBytes, pictureModel.getStartRowIndex() , pictureModel.getEndRowIndex(), pictureModel.getStartColumnIndex(), pictureModel.getEndColumnIndex() , (pictureModel.getPictureType() == null ? Workbook.PICTURE_TYPE_JPEG : pictureModel.getPictureType())); //刪除圖片信息 pictureList.removeAll(sheetPictureList); sheetNameList = pictureList.stream().map(x -> x.getSheetName()).distinct().collect(Collectors.toList()); }
4 調(diào)試代碼
/** * 測試設置圖片 */ @Test public void testPicture() { try { File file = new File("D:/easyexcel/testPicture.xlsx"); FileUtil.createNewFile(file); //生成表格數(shù)據(jù) List<List<Object>> dataList = new ArrayList<>(); dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表頭11", "表頭2", "表頭3", "表頭4"}))); dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表頭17777777777", "表頭2", "表頭3", "表頭4444"}))); dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表頭31", "表頭2", "表頭3", "表頭4"}))); dataList.add(new ArrayList<>(Arrays.asList(new Object[]{11.111, 11.111, "11.111", "表頭4"}))); //導出文件 List<PictureModel> pictureModelList = new ArrayList<>(); String imgUrl = "https://profile.csdnimg.cn/9/5/B/1_qq_38974638"; byte[] bytes = HttpUtil.downloadBytes(imgUrl); String sheetName="模板"; pictureModelList.add(PictureModel.createPictureModel(sheetName,0,10,0,4,bytes)); pictureModelList.add(PictureModel.createPictureModel(sheetName,11,22,0,4,bytes)); FileOutputStream fileOutputStream = new FileOutputStream(file); ExcelWriter excelWriter = EasyExcel.write(fileOutputStream) .inMemory(Boolean.TRUE).registerWriteHandler(new CustomPictureHandler(pictureModelList)).build(); WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build(); excelWriter.write(dataList, writeSheet); //千萬別忘記finish 會幫忙關閉流 excelWriter.finish(); } catch (Exception e) { e.printStackTrace(); } }
5 調(diào)試結(jié)果
注:
1、 注冊自定義處理器之前必須調(diào)用inMemory(Boolean.TRUE)方法。
2、覺得這篇博客寫的不錯的可以前往Gitee點個Star,源碼請查看Gitee的xudongbase項目easyexcel分支。
補充:下面給大家分享基于python語言寫的日常小工具向excel中批量添加圖片和圖片名稱
需求:現(xiàn)有一個200張圖片的文件夾,向 excel 中 A列,寫入圖片的名稱,向ecxel 中的 E 列插入對應的圖片。
from openpyxl import load_workbook from openpyxl.drawing.image import Image import os import re def insert_img_to_excel(filname, by_col,to_col,img_folder): ''' filename : 表格文件路徑 by_col : 依靠哪一列 to_col : 插入到哪一列 img_folder : 圖片路徑 wb = load_workbook(filname) ws = wb.active # 獲取圖片名稱 img_fnn = os.listdir(str(img_folder)) index = 1 # 將圖片名稱寫入到 excel 中 A 列 for img_fp in img_fnn: s= img_fp.replace(".jpg",'') index += 1 i = 'A' + str(index) ws[i].value = s wb.save(filname) wb.close() for ind , c in enumerate(ws[by_col],start=1): # 圖片文件的絕對路徑 img_lujin = os.path.join(img_folder,c.value + '.jpg') try: # 設置圖片大小 img_size = Image(img_lujin) newsize = (150, 200) img_size.width, img_size.height = newsize # 將圖片寫入 excel ws.add_image( img_size, anchor=to_col + str(ind) ) except: print(c.value,'匹配不到圖片') wb.save(filname) if __name__ == '__main__': insert_img_to_excel( filname = r'C:\Users\Administrator\Desktop\act_test\mod.xlsx', by_col = 'A', to_col = 'E', img_folder=r"C:\Users\Administrator\Desktop\act_test\Act_img" )
到此這篇關于Easyexcel 實現(xiàn)批量插入圖片的文章就介紹到這了,更多相關Easyexcel插入圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Java使用easyExcel導出excel數(shù)據(jù)案例
- Java使用EasyExcel動態(tài)添加自增序號列
- Java利用EasyExcel實現(xiàn)合并單元格
- Java使用EasyExcel進行單元格合并的問題詳解
- Java?easyExcel的復雜表頭多級表頭導入
- Java利用EasyExcel解析動態(tài)表頭及導出實現(xiàn)過程
- Java使用EasyExcel實現(xiàn)Excel的導入導出
- Java EasyExcel實現(xiàn)導出多sheet并設置單元格樣式
- Java?EasyExcel實現(xiàn)合并相同內(nèi)容單元格與動態(tài)標題功能
- Java實現(xiàn)讀取Excel文件功能(EasyExcel初使用)
相關文章
Spring boot 實現(xiàn)單個或批量文件上傳功能
這篇文章主要介紹了Spring boot 實現(xiàn)單個或批量文件上傳功能,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-08-08SpringMVC框架中使用Filter實現(xiàn)請求日志打印方式
這篇文章主要介紹了SpringMVC框架中使用Filter實現(xiàn)請求日志打印方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10Spring Security使用數(shù)據(jù)庫認證及用戶密碼加密和解密功能
這篇文章主要介紹了Spring Security使用數(shù)據(jù)庫認證及用戶密碼加密和解密,本文通過代碼與截圖的形式給大家介紹的非常詳細,對大家的工作或?qū)W習具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03Java mutable對象和immutable對象的區(qū)別說明
這篇文章主要介紹了Java mutable對象和immutable對象的區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Java程序開發(fā)中abstract 和 interface的區(qū)別詳解
abstract class和interface在Java語言中都是用來進行抽象類。但是兩者有什么區(qū)別呢,接下來小編給大家?guī)砹薬bstract 和 interface的區(qū)別詳解,感興趣的朋友一起學習吧2016-06-06