081117 使用POI将查询记录输入到excel

先写入一行作为表格头部,然后查询取得一个list,然后循环并调用createCell方法放入excel表中:

public void CreateExcel(String filename){
  HSSFWorkbook wb = new HSSFWorkbook();
  HSSFSheet sheet = wb.createSheet("new sheet");
  HSSFRow row = sheet.createRow((short) 0);
  createCell(wb, row, (short) 0, HSSFCellStyle.ALIGN_CENTER,"Login Name");
  createCell(wb, row, (short) 1, HSSFCellStyle.ALIGN_CENTER_SELECTION,"Login Name");
  createCell(wb, row, (short) 2, HSSFCellStyle.ALIGN_FILL,"Password");
  createCell(wb, row, (short) 3, HSSFCellStyle.ALIGN_GENERAL,"Name");
  createCell(wb, row, (short) 4, HSSFCellStyle.ALIGN_JUSTIFY,"Create Time");
  
  List ls = manager.getAllUserExcel();
 
  int i = 1;
  for (Iterator it = ls.iterator();it.hasNext();i++){
  row = sheet.createRow((short) i);
  Object[] o = (Object[])it.next();
  
  String a="";
  try{
  a = o[0].toString();
  }catch(Exception e){};
  String b="";
  try{
  b = o[1].toString();
  }catch(Exception e){};
  String c="";
  try{
  c = o[2].toString();
  }catch(Exception e){};
  String d="";
  try{
  d = o[3].toString();
  }catch(Exception e){};
  String e="";
  try{
  e = o[4].toString();
  }catch(Exception z){};  
  
  createCell(wb, row, (short) 0, HSSFCellStyle.ALIGN_CENTER,a);
  createCell(wb, row, (short) 1, HSSFCellStyle.ALIGN_CENTER_SELECTION,b);
  createCell(wb, row, (short) 2, HSSFCellStyle.ALIGN_FILL,c);
  createCell(wb, row, (short) 3, HSSFCellStyle.ALIGN_GENERAL,d);
  createCell(wb, row, (short) 4, HSSFCellStyle.ALIGN_JUSTIFY,e); 
  
  } 
  
  // Write the output to a file
  FileOutputStream fileOut = null;
  try {
   fileOut = new FileOutputStream(filename);
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   wb.write(fileOut);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   fileOut.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

createCell方法:
private static void createCell(HSSFWorkbook wb, HSSFRow row, short column, short align,String value)
 {
  HSSFCell cell = row.createCell(column);
  cell.setCellValue(value);
  HSSFCellStyle cellStyle = wb.createCellStyle();
  cellStyle.setAlignment(align);
  cell.setCellStyle(cellStyle);
 }

用到的包:

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值