/**
*
* 创建excel文件
*
*/
1 import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class PoiTest { public static void main(String[] args) throws IOException { //创建一个webbook,对应一个excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//在webbook中添加一个sheet。对应excel文件中的sheet
HSSFSheet sheet = wb.createSheet();
//在sheet中添加表头第0行
HSSFRow row = sheet.createRow(); HSSFCell cell = row.createCell();
cell.setCellValue("aaaaaa");
cell = row.createCell();
cell.setCellValue("bbbbbb");
cell = row.createCell();
cell.setCellValue("cccccc");
//接收utils.userResult方法的返回值
List recetion = new Utils().userResult(); for (int i = ; i < recetion.size()+; i++) { row = sheet.createRow(i); } System.out.println(row.getRowNum()); for (int i = ; i < recetion.size(); i++) {
row = sheet.getRow(i + );
System.out.println(row.getRowNum());
User user = (User)recetion.get(i);
//创建单元格
row.createCell().setCellValue(user.getName());
row.createCell().setCellValue(user.getAge());
row.createCell().setCellValue(user.getOther()); } //保存文件
FileOutputStream fOut = new FileOutputStream("d:\\" + Calendar.getInstance().getTimeInMillis() + ".xls",false);
wb.write(fOut);
fOut.flush();
fOut.close();
}
}
/**
* javabean
*/
public class User { private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
private String age;
private String other; }
/**
* 模拟数据库查询结果
*/
import java.util.ArrayList;
import java.util.List; public class Utils { @SuppressWarnings("rawtypes")
public List userResult() {
User user = new User();
user.setName("张1");
user.setAge("12");
user.setOther("aaaa");
User user1 = new User();
user1.setName("张2");
user1.setAge("12");
user1.setOther("a");
User user2 = new User();
user2.setName("张3");
user2.setAge("12");
user2.setOther("ccc");
User user3 = new User();
user3.setName("张4");
user3.setAge("12");
user3.setOther("bbb"); List<User> list = new ArrayList<User>();
list.add(user);
list.add(user1);
list.add(user2);
list.add(user3);
return list;
}
}
poi jar包下载地址:http://download.csdn.net/download/pumpkin09/7077011