apache poi 动态生成Excel 导入模版并下载
Apache POI 是一个 Java API,用于处理 Microsoft Office 文档,如 Excel、Word 和 PowerPoint。它提供了一组类和方法,可以创建、读取和修改 Office 文档。在本文中,我们将使用 Apache POI 动态生成 Excel 并将其作为下载提供给用户。
- 导入依赖
首先,我们需要在项目中导入 Apache POI 的依赖。在 Maven 项目中,可以将以下依赖添加到 pom.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>
- 创建 Excel 模版
我们需要创建一个 Excel 模版,用于设置表格的样式和布局。可以使用 Microsoft Excel 或 Google Sheets 等电子表格软件来创建模版。在模版中,我们可以添加表头、数据列和格式化设置。
- 使用 Apache POI 读取模版
在 Java 代码中,我们可以使用 Apache POI 读取 Excel 模版,并在其中添加数据。以下是一个示例代码:
// 读取 Excel 模版
FileInputStream inputStream = new FileInputStream("template.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
// 添加数据
Row row = sheet.createRow(1);
row.createCell(0).setCellValue("John Doe");
row.createCell(1).setCellValue(25);
row.createCell(2).setCellValue("Male");
// 保存 Excel 文件
FileOutputStream outputStream = new FileOutputStream("output.xlsx");
workbook.write(outputStream);
workbook.close();
在这个示例代码中,我们首先使用 FileInputStream 读取 Excel 模版文件。然后,我们使用 Workbook 和 Sheet 类获取工作簿和工作表对象。接下来,我们创建一个新的行,并在其中添加数据。最后,我们使用 FileOutputStream 将修改后的 Excel 文件写入磁盘。
- 提供下载链接
最后,我们需要提供一个下载链接,让用户可以下载生成的 Excel 文件。以下是一个示例代码:
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() throws IOException {
// 读取 Excel 模版并添加数据
FileInputStream inputStream = new FileInputStream("template.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.createRow(1);
row.createCell(0).setCellValue("John Doe");
row.createCell(1).setCellValue(25);
row.createCell(2).setCellValue("Male");
// 生成 Excel 文件并设置 HTTP 头信息
File file = new File("output.xlsx");
FileOutputStream outputStream = new FileOutputStream(file);
workbook.write(outputStream);
workbook.close();
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output.xlsx");
// 返回响应
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
在这个示例代码中,我们首先使用 FileInputStream 读取 Excel 模版文件,并在其中添加数据。然后,我们使用 FileOutputStream 将修改后的 Excel 文件写入磁盘。接下来,我们使用 InputStreamResource 将 Excel 文件转换为 InputStream,以便可以将其作为响应主体返回给客户端。最后,我们设置 Content-Disposition 头信息,以便浏览器可以将响应保存为文件
原文地址: https://www.cveoy.top/t/topic/eFAY 著作权归作者所有。请勿转载和采集!