spring-boot+layui 实现预览word、excel
时间: 2024-01-27 19:05:45 浏览: 126
实现预览 Word、Excel 文件可以通过以下步骤:
1. 在 Spring Boot 中添加 Maven 依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 创建一个 Controller 类,提供文件预览的接口。
```java
@RestController
public class FilePreviewController {
@GetMapping("/preview")
public void previewFile(HttpServletResponse response,
@RequestParam(name = "filePath") String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException();
}
String fileName = file.getName();
String extension = FilenameUtils.getExtension(fileName).toLowerCase();
InputStream inputStream = new FileInputStream(file);
response.setHeader("Content-Disposition", "inline;filename=" + fileName);
response.setContentType(getContentType(extension));
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
private String getContentType(String extension) {
switch (extension) {
case "doc":
return "application/msword";
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "xls":
return "application/vnd.ms-excel";
case "xlsx":
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
default:
return "application/octet-stream";
}
}
}
```
3. 在 HTML 页面中调用接口,使用 Layui 的 iframe 模块显示文件预览。
```html
<div class="layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">文件预览</div>
<div class="layui-card-body">
<div class="layui-btn-group">
<button class="layui-btn layui-btn-warm" onclick="previewFile('doc')">预览 Word</button>
<button class="layui-btn layui-btn-warm" onclick="previewFile('xls')">预览 Excel</button>
</div>
<div class="layui-col-md12">
<iframe id="previewIframe" frameborder="0" style="width: 100%;height: 600px;"></iframe>
</div>
</div>
</div>
</div>
<script>
function previewFile(extension) {
let filePath = "/preview?filePath=" + encodeURIComponent("path/to/file." + extension);
$("#previewIframe").attr("src", filePath);
}
</script>
```
这样就可以实现 Word、Excel 文件的预览了。注意,以上示例仅供参考,具体实现方式需要根据实际情况进行调整。
阅读全文