企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
```java @Test public void easyExcel() throws IOException { //1. 示例数据 List<Student> students = new ArrayList<>(); Student student01 = new Student("张三", 25, "男生"); Student student02 = new Student("王五", 29, "男生"); students.add(student01); students.add(student02); //2. 创建文档 SXSSFWorkbook workbook = new SXSSFWorkbook(); //3. 创建一个sheet(表格),参数为表格名称 SXSSFSheet sheet = workbook.createSheet("表格1"); //4. 生成表头 String[] titles = new String[]{"姓名", "年龄", "性别"}; //生成行,行数从0开始,表头就是第0行 SXSSFRow titleRow = sheet.createRow(0); for (int i = 0; i < titles.length; i++) { //生成列,列从第0列开始 SXSSFCell cell = titleRow.createCell(i); //往表格列填值 cell.setCellValue(titles[i]); } //5. 将数据写入表格 for (int i = 0; i < students.size(); i++) { Student student = students.get(i); //第0行已经被表头占用,所以这里从第1行开始 SXSSFRow row = sheet.createRow(i + 1); //生成3列 SXSSFCell nameCell = row.createCell(0); SXSSFCell ageCell = row.createCell(1); SXSSFCell genderCell = row.createCell(2); //往表格列填值 nameCell.setCellValue(student.getName()); ageCell.setCellValue(student.getAge()); genderCell.setCellValue(student.getGender()); } //6. 输出到磁盘文件中 File excelFile = new File("e:/write/001.xlsx"); FileOutputStream out = new FileOutputStream(excelFile); workbook.write(out); //这里使用的是SXSSF,会产生临时文件,输出到磁盘后删除临时文件 workbook.dispose(); workbook.close(); out.close(); } ``` 效果如下: ![](https://img.kancloud.cn/ff/8e/ff8e73e3a5b6c0513605ee018e08ba24_1813x569.png)