| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package com.fdkankan.ucenter.util;
- import cn.hutool.core.bean.BeanUtil;
- import cn.hutool.core.io.FileUtil;
- import cn.hutool.core.util.ObjectUtil;
- import com.alibaba.excel.EasyExcel;
- import com.alibaba.excel.ExcelWriter;
- import com.alibaba.excel.write.metadata.WriteSheet;
- import com.alibaba.excel.write.metadata.fill.FillConfig;
- import com.fdkankan.fyun.face.FYunFileServiceInterface;
- import com.fdkankan.ucenter.entity.Invoice;
- import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
- import org.apache.poi.xssf.usermodel.XSSFDrawing;
- import org.apache.poi.xssf.usermodel.XSSFSheet;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import javax.imageio.ImageIO;
- import javax.servlet.http.HttpServletResponse;
- import java.awt.image.BufferedImage;
- import java.io.*;
- import java.net.URLEncoder;
- import java.util.*;
- public class MyExcelUtil {
- //根据模板导出excel
- public static String excelTemplteToPdf(String localPath, String templateName, Object obj) {
- String fileName = templateName + UUID.randomUUID().toString().replace("-","") + ".xlsx";
- // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
- // 填充list 的时候还要注意 模板中{.} 多了个点 表示list
- //获取文件路径
- InputStream inputStream = MyExcelUtil.class.getClassLoader().getResourceAsStream("template/"+templateName+ ".xlsx");
- ExcelWriter excelWriter = null;
- String filePath = localPath+File.separator + fileName;
- if(!new File(filePath).getParentFile().exists()){
- new File(filePath).mkdirs();
- }
- excelWriter = EasyExcel.write(filePath)
- .withTemplate(inputStream)
- //调用合并策略
- .autoCloseStream(true)
- .build();
- WriteSheet writeSheet = EasyExcel.writerSheet().build();
- // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。
- // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了,所以慎用
- // 简单的说 如果你的模板有list,且list不是最后一行,下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
- // 如果数据量大 list不是最后一行 参照下一个
- FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
- if(excelWriter != null && obj != null){
- excelWriter.fill(obj, fillConfig, writeSheet);
- }
- assert excelWriter != null;
- excelWriter.finish();
- TestForExcel2PDF.excelToPdf(filePath,filePath.replace(".xlsx",".pdf"));
- return filePath.replace(".xlsx",".pdf");
- }
- public static void main(String[] args) {
- Invoice invoice = new Invoice();
- invoice.setInvoiceNumber("11111111111");
- MyExcelUtil.excelTemplteToPdf("D:\\abc\\1212\\111","invoiceTemplate",invoice);
- }
- }
|