日期:2014-05-20  浏览次数:20663 次

通过POI的方式写入execl(分享小经验)
本帖最后由 AA5279AA 于 2013-01-29 16:40:27 编辑
写了一个工具类,传入的形式是
String[][](要写入的数据,包括首行);filepath要写入的文件路径
所需要的jar包:


public static void poiWrite(String[][] str,String filepath){
InputStream inp;
 ifexist(filepath);
try {
inp = new FileInputStream(filepath);
int rownum=str.length;
int columnum=str[0].length;

Workbook wb = WorkbookFactory.create(inp);
         Sheet sheet = wb.getSheetAt(0);
         for(int i=0;i<rownum;i++){
         //System.out.println("i:"+i);
         Row row = sheet.createRow(i);
         for(int j=0;j<columnum;j++){
         /*System.out.println("j:"+j);     */
         Cell cell=row.createCell(j);            
         //设置格式
         cell.setCellType(Cell.CELL_TYPE_STRING);
         //设置值
         cell.setCellValue(str[i][j]);     
         }
         }
         // Write the output to a file
         FileOutputStream fileOut = new FileOutputStream(filepath);
         wb.write(fileOut);
         fileOut.close();
         inp.close();   
         System.out.println("写入完成");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


//传入文件的地址,判断文件是否存在,如果不存在的话创建该文件
//这个功能好像还存在一个小BUG,直接createNewFile();的文件不能用,以后找方法解决。
public static void ifexist(String path){
try {
File file=new File(path);
if(!file.exists()){
System.out.println("文件不存在,创建该文件,文件地址为:"+path);
file.createNewFile();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

------解决方案--------------------
楼主是想把导出excle功能与大家分享?谢谢了!小弟正好需要!

------解决方案--------------------
楼主好人..