引入jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
package com.poi;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class StucentTest {
public static List<Student> studentList() {
Student student = new Student(1, "张三", 1, 143);
Student student1 = new Student(2, "李四", 0, 143);
Student student2 = new Student(3, "张三1", 1, 1344);
Student student3 = new Student(4, "张三3", 0, 141);
Student student4 = new Student(5, "张三4", 1, 121);
Student student5 = new Student(6, "张三56", 1, 14);
Student student6 = new Student(7, "张三6", 0, 14);
Student student7 = new Student(8, "张三7", 1, 87);
Student student8 = new Student(9, "张三12", 0, 34);
Student student9 = new Student(10, "张三9", 1, 112);
Student student10 = new Student(11, "张三12", 0, 14);
List<Student> list = new ArrayList<Student>();
list.add(student);
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
list.add(student6);
list.add(student7);
list.add(student8);
list.add(student9);
list.add(student10);
return list;
}
//设置 样式
public static HSSFCellStyle style(HSSFWorkbook workbook){
//居中
HSSFCellStyle style = workbook.createCellStyle();
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
return style ;
}
public static void main(String[] args) throws IOException {
List<Student> list = studentList();
//创建工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
//创建工作表
Sheet sheet = workbook.createSheet("学生表");
//合并单元格
CellRangeAddress address = new CellRangeAddress(0, 0, 0, 3);
sheet.addMergedRegion(address);
int row = 0;
Row row1 = sheet.createRow(row);
Cell cell = row1.createCell(0);
cell.setCellValue("学生个人信息表");
String[] title = {"id", "姓名", "性别", "年龄"};
row++;
Row row2 = sheet.createRow(row);
for (int i = 0; i < title.length; i++) {
Cell cell1 = row2.createCell(i);
cell1.setCellValue(title[i]);
}
HSSFCellStyle style =style(workbook);
for (int i = 0; i < list.size(); i++) {
Student student = list.get(i);
row++;
Row row3 = sheet.createRow(row);
Cell cell1 = row3.createCell(0);
cell1.setCellStyle(style);
cell1.setCellValue(student.getSid());
Cell cell2 = row3.createCell(1);
cell2.setCellValue(student.getSname());
cell2.setCellStyle(style);
Cell cell3 = row3.createCell(2);
cell3.setCellValue(student.getSex() == 1 ? "男" : "女");
cell3.setCellStyle(style);
Cell cell4 = row3.createCell(3);
cell4.setCellValue(student.getAge());
cell4.setCellStyle(style);
}
FileOutputStream fileOutputStream = new FileOutputStream("D:/student" + ".xls");
workbook.write(fileOutputStream);
System.out.println("成功");
}
}