public class Test { public static void main(String[] args) throws IOException { HSSFWorkbook wk=new HSSFWorkbook(); HSSFSheet sheet=wk.createSheet("学生表"); 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 row2=sheet.createRow(2); row2.createCell(0).setCellValue("1"); row2.createCell(1).setCellValue("刘振宇"); row2.createCell(2).setCellValue("18"); FileOutputStream outputStream=new FileOutputStream("d:\\workbook.xls"); wk.write(outputStream); outputStream.flush(); }
方法二:
创建实体类:
package cn.bdqn.poi; /** * Created by 刘振宇 on 2017/8/28. */ public class entity { 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; } }
测试类:
public class Test { public static void main(String[] args) throws IOException { HSSFWorkbook wk=new HSSFWorkbook(); 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<entity>list=new ArrayList<entity>(); entity entity=new entity(); entity.setId(1); entity.setName("宇"); entity.setAge(18); 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()); } FileOutputStream outputStream=new FileOutputStream("d:\\workbook.xls"); wk.write(outputStream); outputStream.flush(); }