Easyexcel导出文件(多图片)(自用)
生活随笔
收集整理的這篇文章主要介紹了
Easyexcel导出文件(多图片)(自用)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
成品展示:
依賴:
?代碼展示
存在的問題:
成品展示:
?
依賴:
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.3.1</version></dependency>?代碼展示
public void imageWrite(ApplyVo applyVo, HttpServletResponse response) throws IOException {// String fileName = URLEncoder.encode("applyExcel.xlsx", "UTF-8").replaceAll("\\+", "%20");//業(yè)務(wù)數(shù)據(jù)處理applyVo.setSelectState(0);List<ApplyVo> webApply1 = applyDao.getWebApply(applyVo);//導(dǎo)出List<ApplyVo> demoDataList = new ArrayList<>();for (ApplyVo applyVo1 : webApply1) {List<String> path = new ArrayList<>();String specialData = applyVo1.getSpecial();if (!StringUtils.isEmpty(specialData)) {List<JSONObject> list = JSON.parseArray(specialData, JSONObject.class);for (JSONObject item : list) {String url = item.getString("url");String getpath = getpath(url);path.add(new File(getpath).getAbsolutePath());}}ApplyVo applyVo2 = new ApplyVo(applyVo1.getCode(),applyVo1.getCreatedDate(),applyVo1.getName(),applyVo1.getPhone(),applyVo1.getReleaseDate(),path,applyVo1.getCarrier(),applyVo1.getCarrierPhone());demoDataList.add(applyVo2);}genImageExcel(demoDataList, response);}//下載public String getpath(String path) throws IOException {URL url = new URL(path);URLConnection conn = url.openConnection();String fileName1 = "";try (InputStream in = conn.getInputStream()) {byte[] buffer = new byte[1024];int n;fileName1= path.substring(path.lastIndexOf('/') + 1); // 獲取文件名String fileExtension = fileName1.substring(fileName1.lastIndexOf('.') + 1).toLowerCase(); // 獲取文件擴(kuò)展名fileName1 = fileName1.substring(0, fileName1.lastIndexOf('.')); // 去掉擴(kuò)展名,只保留文件名部分fileName1 = fileName1 + "_" + System.currentTimeMillis() + "." + fileExtension; // 在文件名后添加時(shí)間戳fileName1="jpgs/"+fileName1;File file = new File(fileName1);try (OutputStream out = new FileOutputStream(file)) {while ((n = in.read(buffer)) != -1) {out.write(buffer, 0, n);}}}return fileName1;}/*** 生成有圖片的excel 只要傳入List集合的數(shù)據(jù)就可 ,下面的內(nèi)容整體復(fù)制后:除需更改對(duì)象類之外, 注意!!!放行物品-----這四個(gè)字是我的圖片存在的列 需改成自己的 和對(duì)象類里的圖片列對(duì)應(yīng) ** @param demoDataList 數(shù)據(jù)列表**/public static void genImageExcel(List<ApplyVo> demoDataList, HttpServletResponse response) throws IOException {if (CollectionUtils.isEmpty(demoDataList)) {return;}//圖片列最大圖片數(shù)AtomicReference<Integer> maxImageSize = new AtomicReference<>(0);demoDataList.forEach(item -> {if (CollectionUtils.isNotEmpty(item.getPath()) && item.getPath().size() > maxImageSize.get()) {maxImageSize.set(item.getPath().size());}});//設(shè)置列長度所用類AutoColumnWidthStyleStrategy longWidth = new AutoColumnWidthStyleStrategy();demoDataList.forEach(item -> {WriteCellData<Void> writeCellData = new WriteCellData<>();if (CollectionUtils.isNotEmpty(item.getPath())) {//每張圖片間距Integer splitWidth = 2;//每張圖片的長度Integer imageWidth = 80;//圖片列的最大長度Integer sumWidth = maxImageSize.get() * (imageWidth + splitWidth);List<ImageData> imageDataList = new ArrayList<>();List<String> imagePathList = item.getPath();for (int i = 1; i <= imagePathList.size(); i++) {String path = imagePathList.get(i - 1);Integer left = imageWidth * (i - 1) + i * splitWidth;Integer right = sumWidth - imageWidth - left;ImageData imageData = new ImageData();try {imageData.setImage(FileUtils.readFileToByteArray(new File(path)));} catch (IOException e) {e.printStackTrace();}imageData.setImageType(ImageData.ImageType.PICTURE_TYPE_PNG);//距離單元格頂部距離imageData.setTop(1);//距離單元格底部距離imageData.setBottom(1);//距離單元格左邊距離imageData.setLeft(left);//距離單元格右邊距離imageData.setRight(right);imageData.setAnchorType(ClientAnchorData.AnchorType.DONT_MOVE_DO_RESIZE);imageDataList.add(imageData);}writeCellData.setImageDataList(imageDataList);Map<String, Integer> zdyColumnWidth = new HashMap<>();//圖片列名稱,對(duì)應(yīng)導(dǎo)出對(duì)象的列名稱,圖片列長度zdyColumnWidth.put("放行物品", sumWidth / 6);longWidth.setZdyColumnWidth(zdyColumnWidth);}// item.setSpeical(writeCellData);item.setSpecial1(writeCellData);});//寫入數(shù)據(jù)ByteArrayOutputStream out = new ByteArrayOutputStream();// 使用 EasyExcel 將數(shù)據(jù)寫入流中EasyExcel.write(out, ApplyVo.class).registerWriteHandler(longWidth).sheet().doWrite(demoDataList);// 設(shè)置響應(yīng)內(nèi)容response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");// 設(shè)置編碼格式response.setCharacterEncoding("UTF-8");long timestamp = System.currentTimeMillis();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");String strDate = sdf.format(new Date(timestamp));String excelName="applyExcel"+strDate+"(薦:微軟excel)";//設(shè)置文件名String fileName1 = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");//設(shè)置響應(yīng)頭response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName1 + ".xlsx");// 獲取輸出流并寫入數(shù)據(jù)ServletOutputStream servletOut = response.getOutputStream();servletOut.write(out.toByteArray());servletOut.flush();servletOut.close();//刪除圖片demoDataList.forEach(item->{List<String> path = item.getPath();path.forEach(pa->{File file = new File(pa);if (file.exists()) {file.delete();}});});} package com.example.travel.pojo.vo;import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.HeadFontStyle; import com.alibaba.excel.annotation.write.style.HeadStyle;import com.alibaba.excel.metadata.data.WriteCellData; import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableId; import com.example.travel.pojo.excel.IsExceptionConverter; import lombok.*;import java.io.Serializable; import java.util.Date; import java.util.List;@Getter @Setter @EqualsAndHashCode @ContentRowHeight(40) @ColumnWidth(25) //列寬 public class ApplyVo implements Serializable {@TableId(value = "id", type = IdType.AUTO)@ExcelIgnoreprivate Integer id;/*** 發(fā)起單編號(hào)**/@ExcelProperty("申請(qǐng)單編號(hào)")private String code;/*** 創(chuàng)建日期**/@ExcelProperty("申請(qǐng)時(shí)間")private Date createdDate;/*** 姓名**/@ExcelProperty("申請(qǐng)人")private String name;/*** 人員編號(hào)**/@ExcelIgnoreprivate String personCode;/*** 公司id**/@ExcelIgnoreprivate Integer enterpriseId;/*** 公司名稱**/@ExcelIgnoreprivate String enterpriseName;/*** 發(fā)起人公司地址**/@ExcelIgnoreprivate String address;/*** 手機(jī)號(hào)**/@ExcelProperty("申請(qǐng)人手機(jī)號(hào)")private String phone;/*** 放行日期**/@ExcelProperty("放行日期")private Date releaseDate;/*** 物品簡介**/@ExcelProperty(value = "放行物品")private WriteCellData<Void> special1;@ExcelIgnoreprivate List<String> path;@ExcelIgnoreprivate String articleIntroduction;/*** 備注信息**/@ExcelIgnoreprivate String remark;/*** 攜貨人**/@ExcelProperty("攜貨人")private String carrier;/*** 攜貨人手機(jī)號(hào)**/@ExcelProperty("攜貨人手機(jī)號(hào)")private String carrierPhone;/*** 當(dāng)前狀態(tài) 處理完成:0* , 處理中:1* 已取消:2* 已拒絕:3* 通過:4* 拒絕通行:5*/@ExcelProperty(value = "狀態(tài)",converter = IsExceptionConverter.class)private Integer state;/*** 更新日期**/@ExcelIgnoreprivate Date updatedDate;/*** 項(xiàng)目id**/@ExcelIgnoreprivate Integer projectId;/*** 項(xiàng)目名稱**/@ExcelIgnoreprivate String projectName;/*** 工作流id**/@ExcelIgnoreprivate String flowProcessInstanceId;/*** 搜索框**/@ExcelIgnoreprivate String search;//開始時(shí)間@ExcelIgnoreprivate Date stateTime;//結(jié)束時(shí)間@ExcelIgnoreprivate Date endTime;//組織id集合@ExcelIgnoreprivate List<Integer> projectIds;//頁數(shù)@ExcelIgnoreprivate Integer pageNo;//條數(shù)@ExcelIgnoreprivate Integer pageSize;//總數(shù)@ExcelIgnoreprivate Integer total;//數(shù)據(jù)集合@ExcelIgnoreprivate List<ApplyVo> applyVos;// 0為最新創(chuàng)建 1為最近更新@ExcelIgnoreprivate Integer appConditions;//總數(shù)@ExcelIgnoreprivate Integer selectState;/*數(shù)量*/@ExcelIgnoreprivate Integer number;/*放行物品*/@ExcelIgnoreprivate String photo;/*特殊物品*/@ExcelIgnoreprivate String special;@ExcelIgnoreprivate List<Integer> states;public ApplyVo(String code, Date createdDate, String name, String phone, Date releaseDate,List<String> path, String carrier, String carrierPhone ) {this.code = code;this.createdDate = createdDate;this.name = name;this.phone = phone;this.releaseDate = releaseDate;this.carrier = carrier;this.carrierPhone = carrierPhone;this.path = path;}public ApplyVo(){}public ApplyVo(List<String> path) {this.path = path;} }存在的問題:
? ? ? ? ? ? ? ? ? ? ?1:wps打開無法顯示圖片,微軟excel可以,這個(gè)有看到的大佬可以幫忙解答一下,萬分感謝。
? ? ? ? ? ? ? ? ? ? ?2:對(duì)圖片的處理是把網(wǎng)絡(luò)圖片下載到本地后通過路徑存儲(chǔ)到excel后再刪除,非常浪費(fèi)效率(聽了叼毛同事的建議這樣做的,后來懶得改了)。也可以通過流的方式,不用下載和刪除文件
總結(jié)
以上是生活随笔為你收集整理的Easyexcel导出文件(多图片)(自用)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ansys Zemax | 如何模拟部分
- 下一篇: wxWidgets:wxTreebook