SpringBoot整合POIExcel: 实现导入导出Excel功能
以下是一个使用Spring Boot整合Apache POI来导入和导出Excel文件的简单示例。
首先,添加Apache POI依赖到你的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>
导入导出的服务类:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@Service
public class ExcelService {
public Workbook importExcel(MultipartFile file) throws Exception {
InputStream is = file.getInputStream();
Workbook workbook = new XSSFWorkbook(is);
return workbook;
}
public void exportExcel(Workbook workbook, String filename, HttpServletResponse response) throws Exception {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".xlsx");
response.setStatus(HttpServletResponse.SC_OK);
workbook.write(response.getOutputStream());
}
}
控制器类:
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("/api/excel")
public class ExcelController {
@Autowired
private ExcelService excelService;
@PostMapping("/import")
public String importExcel(@RequestParam("file") MultipartFile file) {
try {
Workbook workbook = excelService.importExcel(file);
// 处理workbook中的数据...
return "导入成功";
} catch (Exception e) {
e.printStackTrace();
return "导入失败";
}
}
@GetMapping("/export")
public void exportExcel(HttpServletResponse response) {
Workbook workbook = new XSSFWorkbook();
// 添加数据到workbook...
try {
excelService.exportExcel(workbook, "example", response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个示例提供了导入和导出Ex
评论已关闭