优化这段代码: File file = new File(firstDocPath); InputStream ins = new FileInputStream(file); //注册xdocreport实例并加载FreeMarker模板引擎 IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker); //创建xdocreport上下文对象 IContext context = report.createContext(); //创建要替换的文本变量 context.put("casePersons", casePersonList); context.put("bookResults", bookResultList);//创建字段元数据 FieldsMetadata fm = report.createFieldsMetadata();fm.load("shortVideoResults", ShortVideoAnalysisResultDto.class, true); fm.load("softwareResults", SoftwareAnalysisResultDto.class, true); report.setFieldsMetadata(fm);response.setCharacterEncoding("utf-8"); response.setContentType("application/vnd.msword"); //response.setContentType("application/octet-stream"); String fileName = reportName + ".docx"; response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8")))); report.process(context, response.getOutputStream());
时间: 2024-03-12 16:43:19 浏览: 148
以下是对代码的优化建议:
1. 将文件操作的代码封装在一个方法中,以便复用和维护。
2. 使用try-with-resources自动关闭InputStream和OutputStream,可以避免手动关闭时出现的异常。
3. 使用常量或枚举类型代替魔法值,提高代码可读性。
4. 将重复的字符串拼接操作提取出来,避免在代码中重复出现。
5. 使用Lambda表达式简化代码,提高可读性。
下面是优化后的代码:
```java
private void exportDocxFile(String firstDocPath, String reportName, List<CasePerson> casePersonList, List<BookResult> bookResultList) {
try (InputStream ins = new FileInputStream(firstDocPath);
OutputStream os = response.getOutputStream()) {
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);
IContext context = report.createContext();
context.put("casePersons", casePersonList);
context.put("bookResults", bookResultList);
FieldsMetadata fm = report.createFieldsMetadata();
fm.load("shortVideoResults", ShortVideoAnalysisResultDto.class, true);
fm.load("softwareResults", SoftwareAnalysisResultDto.class, true);
report.setFieldsMetadata(fm);
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.msword");
String fileName = reportName + ".docx";
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
report.process(context, os);
logger.info("导出成功:" + fileName);
} catch (Exception e) {
logger.error("导出失败:" + e.getMessage());
}
}
```
阅读全文