• 根据模板生成html文件并下载


    该模块用于相关内容导出功能,先读取模板文件,再替换模板中的内容,最后直接以流的形式提供下载。主要代码如下:

    String templateContent = "";
    // 读取模板文件
    FileInputStream fileinputstream = new FileInputStream(filePath);
    InputStreamReader isr = new InputStreamReader(fileinputstream, "utf-8");
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while ((line = br.readLine()) != null) {
         templateContent += line;
    }
    br.close();
    // 替换
    templateContent = templateContent.replaceAll("###title###", 【替换的内容】);
    templateContent = templateContent.replaceAll("###htmlContent###", 【替换的内容】); // 当前时间 String time = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()); // 生成文件的名称 String filename = String.valueOf(【文件名】 + "_" + time + "_" + (int) (Math.random() * (9999 - 1000 + 1) + 1000)) + ".html"; // 清空response response.reset(); // 设置文件MIME类型 response.setContentType("text/html; charset=utf-8"); // 设置Content-Disposition response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gb2312"), "ISO8859-1")); // 读取文件 InputStream in = new ByteArrayInputStream(templateContent.getBytes("utf-8")); OutputStream out = response.getOutputStream(); // 写文件 int b; while ((b = in.read()) != -1) { out.write(b); } in.close(); out.close();

    模板代码如下:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>###title###</title>
        <style type="text/css">
            * { margin: 0; padding: 0; }
            body { overflow: auto; font-family: "微软雅黑"; font-size:14px; color:#444;}
        </style>
    </head>
    <body>
    
    ###htmlContent###
    
    </body>
    </html>
  • 相关阅读:
    实操记录之-----Ant Design of Vue 增强版动态合并单元格,自动根据数据进行合并,可自定义横纵向合并
    实操好用~~~~~antd 中 Table表格动态合并~~~
    超级容易理解的函数节流(throttle)
    Flask框架
    Celery框架
    redis数据库如何用Django框架缓存数据
    luffyapi项目 --短信认证的基本操作
    DRF之Jwt 实现自定义和DRF小组件及django-filter插件的使用
    Auth主件的(RBAC) 六表
    DRF之三大认证
  • 原文地址:https://www.cnblogs.com/sjshare/p/5249501.html
Copyright © 2020-2023  润新知