• springboot整合freemarker根据模板导出excel


    maven依赖

    
        org.freemarker
        freemarker
        2.3.30
    
    
    
        spire
        spirexls
        1.0
    

     

     

    import com.manager.exception.ServiceException;
    import com.spire.xls.FileFormat;
    import com.spire.xls.Workbook;
    import freemarker.template.TemplateException;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.io.IOUtils;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.nio.charset.StandardCharsets;
    import java.util.Map;
    
    /**
     * @author yanjj
     * @ClassName HtmlToExcelUtil
     * @date 2022-11-07
     */
    @Slf4j
    public class HtmlToExcelUtil {
    
        public void createExcel(Map dataMap, String templateName, String fileName, HttpServletResponse response){
            log.info("{}:HTML开始生成excel...", fileName);
            response.setContentType("application/octet-stream;charset=utf-8");
            //保存的文件名,必须和页面编码一致,否则乱码
            String excelFileName = response.encodeURL(new String(fileName.getBytes(),StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Disposition",   "attachment;filename=" + excelFileName);
            try(
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    OutputStreamWriter oWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
                    Writer out = new BufferedWriter(oWriter);
                    InputStream inputStream = this.getClass().getResourceAsStream("/templates/".concat(templateName));
            ) {
                if (inputStream == null){
                    throw new ServiceException("{}:HTML开始生成excel生成失败!",fileName);
                }
                createTemplate(new String(IOUtils.toByteArray(inputStream)))
    .process(dataMap, out);
                //下面是重点进行格式转换,转成xlsx
                Workbook wb = new Workbook();
                wb.loadFromXml(new ByteArrayInputStream(outputStream.toByteArray()));
                wb.saveToStream(response.getOutputStream(),FileFormat.Version2013);
            }catch (IOException | TemplateException e) {
                e.printStackTrace();
                log.error("{}:产HTML开始生成excel失败:", fileName, e);
            }
            log.info("{}:HTML开始生成excel生成完成...", fileName);
        }
    }
    /**
     * 动态创建模板
     *
     * @param templateString
     * @return
     * @throws IOException
     */
    public static Template createTemplate(String templateString) throws IOException {
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String id = String.valueOf(TEMPLATE_ID.incrementAndGet());
        stringLoader.putTemplate(id, templateString);
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setDefaultEncoding("utf-8");
        cfg.setTemplateLoader(stringLoader);
        return cfg.getTemplate(id);
    }

    调用

    public static void main(String[] args) {
        Map resultMap = new HashMap<>();
        resultMap.put("company",company);
        resultMap.put("productList",productList);
        new HtmlToExcelUtil().createExcel(resultMap,"量化私募基金运行报表.xml","量化私募基金运行报表.xlsx",response);
    }

    因为我这个excel是两个sheet所以有两个key

    第一个sheet是固定格式固定取值

    ${company.companyName!} //!是指非空才取值

    第二个sheet是循环取值

    <#if productList ??>
        <#list productList as data>
        
            
                ${data.name!}
            
            
                ${data.age!}
            
        
    
    <#else>
            
            
                
            
            
                
            
    

  • 相关阅读:
    SAP-写了一个FUNCTION,用于读取订单中,指定工序的状态。
    日期类练习题
    CCC联盟——UWB MAC(一)
    怎样用Python识别条形码?
    项目任务发布互助申请系统(Java+Web+MySQL)
    springboot 整合es
    【钰娘娘】1373. 二叉搜索子树的最大键值和 DFS
    【C++】map和set的使用
    学习笔记——数据结构与算法之美_极客时间
    如何快速部署本地训练的 Bert-VITS2 语音模型到 Hugging Face
  • 原文地址:https://blog.csdn.net/qq_38377774/article/details/127744577