poi基础



先导入jar包

public void testPoi(){

//创建HSSFWorkbook对象

HSSFWorkbook wb=new HSSFWorkbook();

//创建HSSFSheet对象

HSSFSheet sheet=wb.createSheet(“sheet0”);

//创建HSSFRow行对象

HSSFRow row=sheet.createRow(0);

//创建本行的第1列设置单元格值为id

row.createCell(0).setCellValue(“id”);

row.createCell(1).setCellValue(“姓名”);

//输出excel文件

FileOutputStream output=null;

try {

output=new FileOutputStream(“d:\\workbook.xls”);

wb.write(output);

output.flush();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

    }

}

读取数据列表的一个简单改进

传入两个参数,titles字符串数组是第一行表头,vipList是从数据库获取的列表

public void creatExcel(String[] titles, List<Vip> vipList){

//创建HSSFWorkbook对象

HSSFWorkbook wb=new HSSFWorkbook();

//创建HSSFSheet对象

HSSFSheet sheet=wb.createSheet(“sheet0”);

//创建HSSFRow行对象

HSSFRow row=sheet.createRow(0);

//创建本行的HSSFCell列对象

for (int i=0;i<titles.length;i++) {

row.createCell(i).setCellValue(titles[i]);

    }

for (int x=0;x<vipList.size();x++){

HSSFRow datarow=sheet.createRow(x+1);

for (int i=0;i<titles.length;i++){

switch(i){

case 0:

datarow.createCell(i).setCellValue(vipList.get(x).getId());

break;

case 1:

datarow.createCell(i).setCellValue(vipList.get(x).getName());

break;

case 2:

datarow.createCell(i).setCellValue(vipList.get(x).getTel());

break;

case 3:

datarow.createCell(i).setCellValue(vipList.get(x).getCardcount());

break;

            }
        }
    }

//输出excel文件

FileOutputStream output=null;

try {

output=new FileOutputStream(“d:\\workbook.xls”);

wb.write(output);

output.flush();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

    }

}