Java动态插入数据到html模板并下载为html解决方案

Java动态插入数据到html模板并导出html解决方案

需求

前端页面数据点击下载为一个html,还必须可以打开关闭表格,有颜色样式之类可复制的,所以canvas画成一个pdf导出显然是不行了;
目前解决方案是:
前端: 给出html基础样式模板
后端: 使用FreeMarker模板引擎技术+打包下载+多选zip下载

FreeMarker模板引擎

FreeMarker简介

  1. 主要内容
    Alt
  2. FreeMarker概念
    FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 是一个Java类库。

FreeMarker应用

maven导入

	<dependency>
	  <groupId>org.springframework.boot</groupId>
	  <artifactId>spring-boot-starter-freemarker</artifactId>
	</dependency>

编写工具类

@Slf4j
public class FreemarkerUtils {

    @Data
    public static class ReportFileVo{

        private String fileName;
        private String htmlString;

        public ReportFileVo(){}

        public ReportFileVo(String fileName,String htmlString){
            this.fileName=fileName;
            this.htmlString=htmlString;
        }
    }
    
    /**
     * 获取模板填充数据 返回填充数据后的html字符串
     * @param templatePath 模板名称 (默认从/templates下找)
     * @param map  模板填充数据
     * @return
     */
    public static String getTemplate(String templatePath, Map<String,Object> map) {
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);

            cfg.setClassForTemplateLoading(FreemarkerUtils.class, "/templates");

            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(true);
            Template temp = cfg.getTemplate(templatePath);
            StringWriter stringWriter = new StringWriter();
            temp.process(map, stringWriter);
            return stringWriter.toString();
        }catch (Exception e) {
            log.error("getTemplateFail", e);
        }
        return "";
    }

    /**
     * html字符串解析成html文件前端下载
     * @param vo html
     * @param response
     * @return
     */
    public static Boolean htmlString2fileDownLoad(ReportFileVo vo, HttpServletResponse response)  {
        if(StringUtils.isEmpty(vo.getHtmlString())){
            throw new ServiceException(500,"[html内容为空]");
        }
        String fileName = vo.getFileName();// 文件名
        try {
            fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        OutputStream os=null;
        try {
            byte[] bytes = vo.getHtmlString().getBytes(StandardCharsets.UTF_8);
            os= response.getOutputStream();
            os.write(bytes);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(500,"[下载失败]");
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

	/**
     * 多个html字符串打包成zip下载
     */
    public static void zipFileDownload(Map<String, byte[]> byteList,HttpServletResponse response) {
        try {
            String fileName = System.currentTimeMillis()+".zip";// .zip名
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            OutputStream outputStream = response.getOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
            byteList.forEach((k, v) -> {
                //写入一个条目,我们需要给这个条目起个名字,相当于起一个文件名称
                try {
                    zipOutputStream.putNextEntry(new ZipEntry(k));
                    zipOutputStream.write(v);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("写入文件失败");
                }
            });
            //关闭条目
            zipOutputStream.closeEntry();
            zipOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("压缩文件失败");
        }
    }
}

freemarker导入坐标后开箱即用,无需配置,工具类我这边把全部代码都贴出来了,在你的业务逻辑中处理完数据就可以直接调用

freemarker模板如何编写?我大概展示最简单的几种格式。详细语法在博客中搜的到有很多文章,自行寻找。

//直接插值 !代表为空就用后面那个空字符串
<span class="value">${name!' '}</span>
//对象属性直接插值
<span class="value">${executionRunLog.ruleName!' '}</span>

// if else判断   ??判断不为空
<#if executionRunLog.executionStatus?? && executionRunLog.executionStatus='SUCCESS'>
		<b style="margin-left:0" class="default SUCCESS">COMPLETE</b>
	<#else>
		<b style="margin-left:0" class="default ${executionRunLog.executionStatus!' '}">${executionRunLog.executionStatus!' '}</b>
</#if>

//list for循环 这是list<String>, 如何里面是对象就用.对象属性取值
<#if executionRunLog.linkRequirement??  && (executionRunLog.linkRequirement?size > 0)>
	<#list executionRunLog.linkRequirement as requirementId>
		<button>
			<a href="`https://jira.pg.com.cn/browse/${requirementId!' '}`" target="_blank" rel="noopener noreferrer">${requirementId!' '}</a>
		</button>
	</#list>
</#if>

//map取值
<#if logRecord['SUCCESS']?? >
	<b class="default SUCCESS">Passed ${logRecord['SUCCESS']}</b>
</#if>
//map 循环
<#if setLog.executiveStatistics??  && (setLog.executiveStatistics?size > 0)>
	<#list setLog.executiveStatistics?keys as key>
		${key}:${setLog.executiveStatistics[key]};
	</#list>
</#if>

END

码字不易,如果对你有帮助,请给个三连吧!

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中可以使用Apache POI和Freemarker两个库来实现根据模板导出数据到word的解决方案。 Apache POI是一个Java API,可以用于读写Microsoft Office格式的文档,包括Word、Excel和PowerPoint等。使用Apache POI,可以在Java程序中创建、修改和读取Word文档,将数据填充到Word文档中的模板中,生成新的Word文档。 Freemarker是一个模板引擎,可以将数据填充到模板中,生成新的文本文件,包括HTML、XML、JSON和Word等。使用Freemarker,可以将数据填充到Word文档中的模板中,生成新的Word文档。 具体实现步骤如下: 1. 创建Word文档模板,使用Word软件设计好需要填充数据的文档模板。 2. 使用Apache POI读取Word文档模板,获取到需要填充数据的位置和格式。 3. 使用Freemarker将数据填充到Word文档模板中,生成新的Word文档。 4. 将生成的新的Word文档保存到文件或输出到浏览器。 这是一个基本的实现流程,具体实现细节可以参考相关的文档和示例代码。以下是一个基本的示例代码: ``` // 1. 创建Word文档模板 FileInputStream fis = new FileInputStream("template.docx"); XWPFDocument templateDoc = new XWPFDocument(fis); fis.close(); // 2. 使用Apache POI读取Word文档模板 for (XWPFParagraph paragraph : templateDoc.getParagraphs()) { List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); if (text != null && text.contains("${")) { // 找到需要填充的位置 // 可以使用正则表达式或者字符串替换等方式进行定位 } } } // 3. 使用Freemarker将数据填充到Word文档模板中 Configuration cfg = new Configuration(Configuration.VERSION_2_3_30); cfg.setDefaultEncoding("UTF-8"); cfg.setClassForTemplateLoading(this.getClass(), "/templates"); Template template = cfg.getTemplate("template.ftl"); Map<String, Object> data = new HashMap<>(); data.put("name", "张三"); data.put("age", 20); StringWriter sw = new StringWriter(); template.process(data, sw); String content = sw.toString(); // 4. 将生成的新的Word文档保存到文件或输出到浏览器 XWPFDocument newDoc = new XWPFDocument(); XWPFParagraph newParagraph = newDoc.createParagraph(); XWPFRun newRun = newParagraph.createRun(); newRun.setText(content); FileOutputStream fos = new FileOutputStream("output.docx"); newDoc.write(fos); fos.close(); newDoc.close(); ``` 上述代码使用了一个模板文件`template.ftl`,该文件中包含了需要填充的数据的位置和格式。在代码中,使用Freemarker将数据填充到模板中,生成新的内容`content`,然后将新的内容生成为一个新的Word文档并保存到文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值