/*** * 生成一个xls文件 * @param fileName 需要生成的文件名称 */ public static void writeExcel(String fileName){ WritableWorkbook wwb = null; try{ //用Workbook类的工厂方法来创建一个可以写入的工作薄(Workbook)对象 wwb = Workbook.createWorkbook(new File(fileName)); }catch(IOException e){ e.printStackTrace(); } if(wwb!=null){ //创建工作表 //通过工作薄来创建工作表,createSheet()需两个参数,一个是工作表名称,一个是工作表在工作薄中的位置 WritableSheet ws = wwb.createSheet("测试Excel", 0); //下面开始添加单元格 for(int i=0 ;i <100;i++){ for(int j=0;j<5;j++){ //在Excel中,第一个参数标识列,第二个参数标识行 Label la = new Label(j,i,"这是第"+(i+1)+"行,这是第"+(j+1)+"列"); try { //将生成的单元格添加到工作表里面去 ws.addCell(la); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } } try { wwb.write(); } catch (IOException e) { e.printStackTrace(); }finally{ try { wwb.close(); } catch (WriteException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
插入图片
/***
* 在Excel文件中添加图片
* @param writeable 工作表
* @param col 列数
* @param row 行数
* @param width 高
* @param height 长度
* @param imgFile 图片路径
*/
public static void insertImg(WritableSheet writeable, int col,
int row, int width, int height, File imgFile ){
WritableImage wi = new WritableImage(col,row,width,height,imgFile);
writeable.addImage(wi);
}