【发布时间】:2021-11-02 05:14:26
【问题描述】:
我正在尝试使用 Spring Boot 从 JDBC 结果集中提取 Word 文档。一切正常,只是当出现一些错误时,我会收到 500 错误以及一个空文件。如何防止生成空文件。
@GetMapping(produces = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", value = "export/word")
@ApiOperation(value = "Export table as word")
public void generateword(HttpServletResponse response, @RequestParam(required = true) String tableName,
@RequestParam(required = false) String search, @RequestParam(required = false) String searchColumn,
@RequestHeader(required = false, value = "x-remote-user") String username)
throws DataAccessException, IOException {
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String currentDateTime = dateFormatter.format(new Date());
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=" + tableName + "_" + currentDateTime + ".docx";
response.setHeader(headerKey, headerValue);
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
if (StringUtils.hasLength(search)) {
describeDatabaseRepository.generateWord(tableName, username, search, searchColumn, response);
} else {
describeDatabaseRepository.generateWord(tableName, username, response);
}
}
【问题讨论】:
-
使用try catch块——做异常处理——在catch块中,你可以改变响应内容类型——试试吧
标签: spring spring-boot spring-jdbc