MyExcelUtil.java 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. package com.fdkankan.sale.util;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.img.ImgUtil;
  4. import cn.hutool.core.io.FileUtil;
  5. import cn.hutool.core.util.ObjectUtil;
  6. import com.alibaba.excel.read.metadata.ReadSheet;
  7. import com.alibaba.excel.write.handler.SheetWriteHandler;
  8. import com.alibaba.excel.write.metadata.fill.FillWrapper;
  9. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  10. import com.fdkankan.sale.common.CacheUtil;
  11. import com.fdkankan.sale.common.FilePath;
  12. import com.fdkankan.sale.entity.Customer;
  13. import com.fdkankan.sale.entity.PriceList;
  14. import com.fdkankan.sale.service.IPriceListService;
  15. import com.fdkankan.sale.util.pdf.ExportImg;
  16. import com.fdkankan.sale.util.pdf.MyHandler;
  17. import com.fdkankan.sale.util.pdf.TestForExcel2PDF;
  18. import com.fdkankan.sale.vo.response.PriceListExcelVo;
  19. import javassist.expr.FieldAccess;
  20. import org.apache.poi.ss.usermodel.ClientAnchor;
  21. import org.apache.poi.ss.usermodel.Sheet;
  22. import org.apache.poi.ss.usermodel.Workbook;
  23. import org.apache.poi.ss.usermodel.WorkbookFactory;
  24. import org.apache.poi.ss.util.CellRangeAddress;
  25. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
  26. import org.apache.poi.xssf.usermodel.XSSFDrawing;
  27. import org.apache.poi.xssf.usermodel.XSSFSheet;
  28. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.core.io.ClassPathResource;
  31. import com.alibaba.excel.EasyExcel;
  32. import com.alibaba.excel.ExcelWriter;
  33. import com.alibaba.excel.write.metadata.WriteSheet;
  34. import com.alibaba.excel.write.metadata.fill.FillConfig;
  35. import org.springframework.stereotype.Component;
  36. import javax.imageio.ImageIO;
  37. import javax.servlet.http.HttpServletResponse;
  38. import java.awt.image.BufferedImage;
  39. import java.io.*;
  40. import java.net.URLEncoder;
  41. import java.util.*;
  42. @Component
  43. public class MyExcelUtil {
  44. @Autowired
  45. FYunFileServiceInterface fYunFileServiceInterface;
  46. //根据模板导出excel
  47. public void listFill(HttpServletResponse response, String excelName, Object obj, Object obj2, ExportImg exportImg,Integer type) {
  48. String fileName = excelName + ".xlsx";
  49. // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
  50. // 填充list 的时候还要注意 模板中{.} 多了个点 表示list
  51. //获取文件路径
  52. String templateName = null;
  53. if(type == 0){
  54. templateName = "orderTemplate.xlsx";
  55. }
  56. if(type == 1){
  57. templateName = "repairTemplate.xlsx";
  58. }
  59. String ossPath = String.format(FilePath.oss_file_path,FilePath.common,templateName);
  60. String localPath = FilePath.file_path + FilePath.common +"/" + templateName;
  61. File file = new File(localPath);
  62. if(!file.exists()){
  63. fYunFileServiceInterface.downloadFile(ossPath,localPath );
  64. }
  65. String ossPathImage = String.format(FilePath.oss_file_path,FilePath.common,"logo.png");
  66. String localPathImage = FilePath.file_path + FilePath.common +"/" + "logo.png";
  67. File fileImage = new File(localPathImage);
  68. if(!fileImage.exists()){
  69. fYunFileServiceInterface.downloadFile(ossPathImage,localPathImage );
  70. }
  71. String templateFileName = file.getPath();
  72. String localFilePath = FilePath.file_path + FilePath.common + "/" + fileName;
  73. File localFile = new File(localFilePath);
  74. ExcelWriter excelWriter = null;
  75. //需要合并的行
  76. List<Integer> mergeRowsIndex =new ArrayList<>();
  77. //需要合并的列
  78. List<Integer> mergeColumnIndex = new ArrayList<>();
  79. Integer index = 0;
  80. if(type == 0){
  81. index = 13;
  82. mergeRowsIndex = Arrays.asList(1);
  83. }
  84. if(type == 1){
  85. index = 47;
  86. mergeRowsIndex = Arrays.asList(2);
  87. }
  88. if(obj2 != null){
  89. List<PriceListExcelVo> list = (List<PriceListExcelVo>)obj2;
  90. Integer i = 0;
  91. for (PriceListExcelVo excelVo : list) {
  92. mergeColumnIndex.add(index + i);
  93. i++;
  94. }
  95. }
  96. excelWriter = EasyExcel.write(localFile)
  97. .withTemplate(templateFileName)
  98. //调用合并策略
  99. .registerWriteHandler(new ExcelFillCellMergeStrategy(1, mergeRowsIndex, mergeColumnIndex))
  100. .autoCloseStream(true)
  101. .build();
  102. WriteSheet writeSheet = EasyExcel.writerSheet().build();
  103. // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。
  104. // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了,所以慎用
  105. // 简单的说 如果你的模板有list,且list不是最后一行,下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
  106. // 如果数据量大 list不是最后一行 参照下一个
  107. FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
  108. if(excelWriter != null && obj != null){
  109. excelWriter.fill(obj, fillConfig, writeSheet);
  110. }
  111. if(excelWriter != null &&obj2 != null){
  112. excelWriter.fill(obj2, fillConfig, writeSheet);
  113. }
  114. if(excelWriter != null &&exportImg != null){
  115. Map<String, Object> map = BeanUtil.beanToMap(exportImg);
  116. imageHandleByParam(map);
  117. excelWriter.fill(map, fillConfig, writeSheet);
  118. }
  119. assert excelWriter != null;
  120. excelWriter.finish();
  121. this.addImage(localFilePath,localPathImage);
  122. TestForExcel2PDF.excelToPdf(localFilePath,localFilePath.replace(".xlsx",".pdf"));
  123. response.setContentType("application/force-download");
  124. response.setCharacterEncoding("utf-8");
  125. try {
  126. fileName = URLEncoder.encode(fileName, "UTF-8");
  127. } catch (UnsupportedEncodingException e) {
  128. e.printStackTrace();
  129. }
  130. response.setHeader("Content-disposition", "attachment;filename=" + fileName.replace(".xlsx",".pdf"));
  131. // 以流的形式下载文件。
  132. try {
  133. InputStream fis = new BufferedInputStream(new FileInputStream(localFilePath.replace(".xlsx",".pdf")));
  134. byte[] buffer = new byte[fis.available()];
  135. fis.read(buffer);
  136. fis.close();
  137. OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
  138. toClient.write(buffer);
  139. toClient.flush();
  140. toClient.close();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. }
  144. }
  145. /**
  146. * 图片处理
  147. *
  148. * @param param
  149. */
  150. private void imageHandleByParam(Map<String, Object> param) {
  151. for (Map.Entry<String, Object> entry : param.entrySet()) {
  152. String mapKey = entry.getKey();
  153. if(ObjectUtil.isNull(entry.getValue())){
  154. continue;
  155. }
  156. String ossPath = entry.getValue().toString();
  157. String downloadPath = FilePath.file_path + ossPath.replaceAll(CacheUtil.host,"");
  158. try {
  159. File file = new File(downloadPath);
  160. if(!file.exists()){
  161. fYunFileServiceInterface.downloadFile(ossPath.replaceAll(CacheUtil.host,""),downloadPath );
  162. }
  163. // 填充图片
  164. ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
  165. BufferedImage bufferImg = ImageIO.read(new File(downloadPath));
  166. // 图片后缀格式
  167. ImageIO.write(bufferImg, "png", byteArrayOut);
  168. bufferImg.flush();
  169. // 注意:这里需要put回原来的key里
  170. param.put(mapKey, byteArrayOut.toByteArray());
  171. } catch (IOException e) {
  172. e.printStackTrace();
  173. }finally {
  174. FileUtil.del(downloadPath);
  175. }
  176. }
  177. }
  178. public void addImage(String filePath,String imagePath) {
  179. FileOutputStream fileOut = null ;
  180. BufferedImage bufferImg = null ;
  181. try {
  182. // 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
  183. ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
  184. bufferImg = ImageIO.read( new File( imagePath ));
  185. ImageIO.write(bufferImg, "png" ,byteArrayOut);
  186. // 创建一个工作薄
  187. XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File(filePath)));
  188. XSSFSheet sheet1 = wb.getSheetAt(0);
  189. // XSSFRow row = sheet1.createRow(2);
  190. int lastRowNum = sheet1.getLastRowNum();
  191. XSSFDrawing patriarch = sheet1.createDrawingPatriarch();
  192. XSSFClientAnchor anchor = new XSSFClientAnchor( 0 , 0 , 512 , 255 ,( short ) 6 , lastRowNum-6 ,( short ) 7 , lastRowNum -4 );
  193. // 插入图片
  194. patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),XSSFWorkbook.PICTURE_TYPE_PNG));
  195. fileOut = new FileOutputStream( filePath );
  196. // 写入excel文件
  197. wb.write(fileOut);
  198. fileOut.close();
  199. } catch (IOException io) {
  200. io.printStackTrace();
  201. System.out.println( " io erorr : " + io.getMessage());
  202. } finally {
  203. if (fileOut != null ) {
  204. try {
  205. fileOut.close();
  206. }
  207. catch (IOException e) {
  208. // TODO Auto-generated catch block
  209. e.printStackTrace();
  210. }
  211. }
  212. }
  213. }
  214. }