poi模板导出

public class excel2POI {
 @SuppressWarnings("unchecked")
 public void excel(String outputFile, List dataList)throws FileNotFoundException, IOException {
  String is = "test.xls";
  System.out.println(is);
  POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(is)); // 用模板文件构造poi
  HSSFWorkbook templatewb = new HSSFWorkbook(fs); // 创建模板工作表
  HSSFSheet templateSheet = templatewb.getSheet("spotInfoExcel"); // 直接取模板第一个sheet对象
  int columns = templateSheet.getRow((short) 0).getPhysicalNumberOfCells(); // 取得Excel文件的总列数
  HSSFCellStyle styleArray[] = new HSSFCellStyle[columns]; // 创建样式数组
  // 一次性创建所有列的样式放在数组里
  for (int s = 0; s < columns; s++) {
   // 得到数组实例
   styleArray[s] = templatewb.createCellStyle();
  }
  HSSFRow row = null;
  Map map = null;
  HSSFCell cell = null;
  int num = dataList.size();
  for (int j = 0; j < num; j++) {
   row = templateSheet.createRow(j + 1);
   map = (Map) dataList.get(j);
   for (int k = 0; k < map.keySet().size(); k++) {
    cell = row.createCell(k);
    if (null != map.get(k)) {
     HSSFRichTextString tsetString = new HSSFRichTextString(map
       .get(k).toString());
     cell.setCellValue(tsetString.toString());// 列中放入值
    }
   }
   map.clear();
   map = null;
  }
  // 设置输入流
  FileOutputStream fOut = new FileOutputStream(outputFile);
  templatewb.write(fOut); // 将模板的内容写到输出文件上
  fOut.flush();
  // 操作结束,关闭文件
  fOut.close();
 }

 
 

 public static void main(String[] args) {
  List list = new ArrayList();
  Map map = new HashMap();
  map.put(0, "a");
  map.put(1, "b");
  map.put(2, "c");
  Map map1 = new HashMap();
  map1.put(0, "aa");
  map1.put(1, "bb");
  map1.put(2, "cc");
  list.add(map);
  list.add(map1);
  try {
   excel2POI ss = new excel2POI();
   ss.excel("d:/test1.xls", list);
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

猜你喜欢

转载自leilei336624.iteye.com/blog/1468622
今日推荐