该模块用于相关内容导出功能,先读取模板文件,再替换模板中的内容,最后直接以流的形式提供下载。主要代码如下:
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> |
时间: 2024-10-14 02:26:00