poi导出
一、 POI简介
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
二、 HSSF概况
HSSF 是Horrible SpreadSheet Format的缩写,通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。
三: POI EXCEL文档结构类
HSSFWorkbook excel文档对象
HSSFSheet excel的sheet HSSFRow excel的行
HSSFCell excel的单元格 HSSFFont excel字体
HSSFName 名称 HSSFDataFormat 日期格式
HSSFHeader sheet头
HSSFFooter sheet尾
HSSFCellStyle cell样式
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 错误信息表
以上为POI的基本介绍 下面通过例子展开详解:(运用的开发软件为IDEA)
pom的节点
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17-beta1</version>
</dependency>
创建Student实体类:将其属性进行get,set封装
public class Student {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
创建测试类Text:
public class Text {
@Test
public void test() throws IOException {
//创建HSSFWorkbook对象
HSSFWorkbook wk=new HSSFWorkbook();
//创建HSSFSHeet对象(excel表单)
HSSFSheet sheet=wk.createSheet("学生表");
HSSFRow row=sheet.createRow(0);
HSSFCell cell=row.createCell((short)0);
cell.setCellValue("学生编号");
cell=row.createCell((short)1);
cell.setCellValue("学生姓名");
cell=row.createCell((short)2);
cell.setCellValue("学生年龄");
List<Student> list=new ArrayList<Student>();
Student student=new Student();
student.setId(1);
student.setName("轩轩");
student.setAge(20);
Student student1=new Student();
student1.setId(2);
student1.setName("娜娜");
student1.setAge(16);
list.add(student);
list.add(student1);
for (short i=0;i<list.size();i++){
row=sheet.createRow(i+1);
row.createCell(0).setCellValue(list.get(i).getId());
row.createCell(1).setCellValue(list.get(i).getName());
row.createCell(2).setCellValue(list.get(i).getAge());
}
/*第一种方式*/
/* HSSFRow row=sheet.createRow(0);
HSSFCell cell=row.createCell(0);
cell.setCellValue("学生成绩表");
sheet.addMergedRegion(new CellRangeAddress(0,0,0,2));
HSSFRow row1=sheet.createRow(1);
row1.createCell(0).setCellValue("学生编号");
row1.createCell(1).setCellValue("学生姓名");
row1.createCell(2).setCellValue("学生年龄");
HSSFRow row3=sheet.createRow(2);
row3.createCell(0).setCellValue("1");
row3.createCell(1).setCellValue("啦啦");
row3.createCell(2).setCellValue("16");*/
FileOutputStream outputStream=new FileOutputStream("E:\\workbooks.xls");
wk.write(outputStream);
outputStream.flush();
}
}
第一种方式结果:
第二种方式结果:
浙公网安备 33010602011771号