测试类中的代码 @SpringBootTest public class WritePOI { //定义文件路径 static String fileName = "D:\\files\\students.xlsx"; public static void main(String[] args) throws IOException, ParseException { //1.创建工作簿对象 需要选择xls或者xlsx. 这里选择的是xlsx。 Workbook workbook = new XSSFWorkbook(); //2.创建工作表对象 (单元的名字) Sheet sheet = workbook.createSheet("学生信息"); //3.创建行对象 (表头行 从0开始计算) Row headerRow = sheet.createRow(0); //3.2创建表头样式 //设置表头样式对象 CellStyle headerStyle = workbook.createCellStyle(); //设置水平居中对齐 headerStyle.setAlignment(HorizontalAlignment.CENTER); //设置垂直居中对齐 headerStyle.setVerticalAlignment(VerticalAlignment.CENTER); //创建表头字体对象 Font headerFont = workbook.createFont(); //设置表头字体加粗 headerFont.setBold(true); //设置表头字体颜色为白的 headerFont.setColor(IndexedColors.WHITE.getIndex()); //设置表头字体大小 //将字体应用到表头样式 headerStyle.setFont(headerFont); //设置表头单元格填充颜色为蓝色 headerStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); //设置表头单元格填充颜色模式为实心填充 headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); //3.3创建表头单元格对象 Cell cell = headerRow.createCell(0); cell.setCellValue("姓名"); cell.setCellStyle(headerStyle); cell = headerRow.createCell(1); cell.setCellValue("年龄"); cell.setCellStyle(headerStyle); cell = headerRow.createCell(2); cell.setCellValue("性别"); cell.setCellStyle(headerStyle); cell = headerRow.createCell(3); cell.setCellValue("生日"); cell.setCellStyle(headerStyle); // 设置列宽(像素) 可选 // sheet.setColumnWidth(0, 10 * 256); // sheet.setColumnWidth(1, 5 * 256); // sheet.setColumnWidth(2, 5 * 256); // sheet.setColumnWidth(3, 10 * 256); //填充数据 List<Student> students = getStudents(); int rowIndex = 1; for (Student student : students) { Row row = sheet.createRow(rowIndex++); row.createCell(0).setCellValue(student.getName()); row.createCell(1).setCellValue(student.getAge()); row.createCell(2).setCellValue(student.getGender()); row.createCell(3).setCellValue(student.getBirthday()); } // 将工作簿写入输出流 FileOutputStream outputStream = new FileOutputStream(fileName); workbook.write(outputStream); outputStream.close(); System.out.println("Excel文件生成成功!"); } private static List<Student> getStudents() throws ParseException { String d1 = "2000-08-10"; String d2 = "2000-07-17"; String d3 = "2000-02-11"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = dateFormat.parse(d1); Date date1 = dateFormat.parse(d2); Date date2 = dateFormat.parse(d3); List<Student> students = new ArrayList<>(); students.add(new Student("张三", 18, "男", date)); students.add(new Student("李四", 19, "女", date1)); students.add(new Student("王五", 20, "男", date2)); return students; } } 创建学生类
@Data @NoArgsConstructor @AllArgsConstructor public class Student { private String name; private int age; private String gender; private Date birthday; }