Apache POI 是 Apache 软件基金会的开源项目,它提供 API 用于读取和写入 Microsoft Office 格式的文件,如 Excel、Word 等。在 Spring Boot 应用中,结合使用 Apache POI 可以方便地处理 Excel 文件
一 引入依赖:
<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示例:
import org.apache.poi.ss.usermodel.*; // 导入Apache POI的通用接口
import org.apache.poi.xssf.usermodel.XSSFWorkbook; // 导入用于处理.xlsx文件的类 import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; public class ExcelReader { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream(new File("path/to/your/excel/file.xlsx"))) { // 创建一个工作簿对象,从输入流中读取Excel文件 Workbook workbook = new XSSFWorkbook(fis); // 获取第一个工作表 Sheet sheet = workbook.getSheetAt(0); // 遍历工作表中的所有行 for (Row row : sheet) { // 遍历行中的所有单元格 for (Cell cell : row) { // 获取单元格的值,并打印 String cellValue = getCellValueAsString(cell); System.out.print(cellValue + "\t"); // \t 是制表符,用于分隔单元格内容 } System.out.println(); // 每行结束后换行 } // 关闭工作簿 workbook.close(); } catch (IOException e) { // 如果发生IO异常,打印堆栈跟踪 e.printStackTrace(); } } /** * 根据单元格类型获取单元格的值,并返回字符串表示 * * @param cell 要获取值的单元格 * @return 单元格值的字符串表示 */ private static String getCellValueAsString(Cell cell) { switch (cell.getCellType()) { case STRING: return cell.getStringCellValue(); // 字符串类型直接返回 case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { return DateUtil.formatCellValueToDate(cell).toString(); // 日期类型格式化为字符串 } else { return Double.toString(cell.getNumericCellValue()); // 数字类型转换为字符串 } case BOOLEAN: return Boolean.toString(cell.getBooleanCellValue()); // 布尔类型转换为字符串 case FORMULA: return cell.getCellFormula(); // 公式类型返回公式字符串 default: return ""; // 其他类型返回空字符串 } }
}
三 写入Excel示例:
import org.apache.poi.ss.usermodel.*; // 导入Apache POI的通用接口
import org.apache.poi.xssf.usermodel.XSSFWorkbook; // 导入用于处理.xlsx文件的类 import java.io.FileOutputStream;
import java.io.IOException; public class ExcelWriter { public static void main(String[] args) { // 创建一个新的工作簿对象 Workbook workbook = new XSSFWorkbook(); // 在工作簿中创建一个名为"Sheet1"的工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 在工作表中创建第一行 Row row = sheet.createRow(0); // 在第一行中创建第一个单元格,并设置其值为"Hello, World!" Cell cell = row.createCell(0); cell.setCellValue("Hello, World!"); try (FileOutputStream fos = new FileOutputStream("path/to/your/output/excel/file.xlsx")) { // 将工作簿的内容写入输出流,即写入文件 workbook.write(fos); // 刷新输出流,确保所有数据都写入文件 fos.flush(); } catch (IOException e) { // 如果发生IO异常,打印堆栈跟踪 e.printStackTrace(); } finally { try { // 关闭工作簿,释放资源 workbook.close(); } catch (IOException e) { // 如果关闭工作簿时发生异常,打印堆栈跟踪 e.printStackTrace(); } } }
}
四 浏览器下载Excel示例(api示例):
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; @RestController
public class StudentExcelController { @GetMapping("/exportStudents") public ResponseEntity<Void> exportStudents(HttpServletResponse response) throws IOException { // 创建Excel文档 XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("学生信息"); // 创建表头 XSSFRow header = sheet.createRow(0); header.createCell(0).setCellValue("姓名"); header.createCell(1).setCellValue("学号"); header.createCell(2).setCellValue("班级"); header.createCell(3).setCellValue("成绩"); // 填充数据 List<Student> students = getStudentList(); int rowIndex = 1; for (Student student : students) { XSSFRow row = sheet.createRow(rowIndex++); row.createCell(0).setCellValue(student.getName()); row.createCell(1).setCellValue(student.getStudentId()); row.createCell(2).setCellValue(student.getClassName()); row.createCell(3).setCellValue(student.getScore()); } // 设置响应头信息 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=students.xlsx"); // 将Excel文档写入响应流中 workbook.write(response.getOutputStream()); workbook.close(); // 记得关闭workbook return new ResponseEntity<>(HttpStatus.OK); } // 模拟获取学生数据 private List<Student> getStudentList() { List<Student> students = new ArrayList<>(); students.add(new Student("张三", "20230001", "一班", 90)); students.add(new Student("李四", "20230002", "二班", 85)); students.add(new Student("王五", "20230003", "三班", 92)); return students; } // 学生实体类 static class Student { private String name; private String studentId; private String className; private double score; public Student(String name, String studentId, String className, double score) { this.name = name; this.studentId = studentId; this.className = className; this.score = score; } public String getName() { return name; } public String getStudentId() { return studentId; } public String getClassName() { return className; } public double getScore() { return score; } }
}