package com.kwan.springbootkwan.utils; import com.kwan.springbootkwan.entity.User; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ExcelWriter { private static List header = Arrays.asList("1"); public static void writeListToExcel(List dataList, String filePath, String sheetName) { try (Workbook workbook = new XSSFWorkbook()) { Sheet sheet = workbook.createSheet(sheetName); // 创建标题行 Row headerRow = sheet.createRow(0); for (int i = 0; i < dataList.size(); i++) { Cell cell = headerRow.createCell(i); cell.setCellValue("季节"); } // 写入数据行 int rowNum = 1; for (Object data : dataList) { Row row = sheet.createRow(rowNum++); CellStyle style = workbook.createCellStyle(); style.setWrapText(true); Cell cell = row.createCell(0); cell.setCellValue(data.toString()); cell.setCellStyle(style); } // 将Workbook写入文件 try (FileOutputStream fileOut = new FileOutputStream(filePath)) { workbook.write(fileOut); } System.out.println("Excel文件成功创建!"); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { // 你的数据列表 List dataList = new ArrayList<>(); User user1 = new User(); user1.setId(1); user1.setName("张三"); user1.setSex("男"); dataList.add(user1); User user2 = new User(); user2.setId(2); user2.setName("程满"); user2.setSex("女"); dataList.add(user2); User user3 = new User(); user3.setId(3); user3.setName("禹辰"); user3.setSex("男"); dataList.add(user3); // Excel文件路径和工作表名称 String filePath = "/Users/qinyingjie/Downloads/file.xlsx"; String sheetName = "Sheet1"; // 调用写入Excel的方法 writeListToExcel(dataList, filePath, sheetName); } }