`
王树雄
  • 浏览: 239287 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

浅谈jxl解析excel —————复制、修改excel表

阅读更多
  
  //既然是复制,那么我们首先要进行读取的操作。但是在jxl当中读取操作只能只读,而不能修改。也没有一种方式让我们直接在读取的时候定义成可读可写的
  //但是jxl提供了一种方法。我们读取一份excel文件。然后将生产的workbook对象传入可读写的另外一个对象。这样的话。就可以实现一个读写的操作;
  Workbook   wb=null;
  WritableWorkbook    wwb=null;
  try {
   //从源文件中进行读取
     wb=Workbook.getWorkbook(new File("c.xls"));
   
            //然后复制一份到目标目录下、
   //仔细看会发现。其实复制操作时读取和创建操作的一个综合打包。
   
     wwb=Workbook.createWorkbook(new File("b.xls"),wb);
   
   
   //得到第一个表;
   
   WritableSheet   ws= wwb.getSheet(0);
   for(int i=0;i<10;i++){
    for(int j=0;j<10;j++){
     //得到具体的一个单元格
     Cell  c=ws.getCell(i, j);
     
     //判断其类型;一般情况下有这么几种类型。是标签型的。数字型。日期型。
     
     if(c.getType()==CellType.LABEL){
      Label  la=(Label) c;
      la.setString("改变了!");
     }
     if(c.getType()==CellType.NUMBER){
      Number no=(Number)c;
      no.setValue(1);
     }
     if(c.getType()==CellType.DATE){
      DateTime no=(DateTime)c;
      no.setDate(new java.util.Date());
     }
    }
   }
   //每种不同的格式具有不一样的修改方法;
   //标签型的话。用setString() 数字型的用setvalue 。日期型的用setDate();
   //另外注意一点。这儿的修改不能像是获取一样一锅端。管它什么日期。标签。数字、全部将它的内容获取然后变成字符串。必须要判断你修改的这一个单元格的性质;
   
   
  
  } catch (BiffException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  finally{
   //关闭
   try {
    wwb.write();
    wwb.close();
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   wb.close();
   
  }
  System.out.println("修改了");   

  

 

   另外。如果你需要给修改的单元格限定格式的话。那么。只需要在修改之前给它指定格式就行

 

 

 

NumberFormat fivedps = new NumberFormat("#.#####"); 
WritableCellFormat cellFormat = new WritableCellFormat(fivedps); 
cell.setFormat(cellFormat); 

   

   然后再进行修改即可。 

 

    通过运行我们发现。修改操作不是在原文件上操作的。因为原文件只有读取的操作。而是在复制的目标文件上进行操作。

 

   官网文档里面有这么一段话:

 

  

 However, if we need to modify this spreadsheet a handle to the various write interfaces is needed,  which can be obtained using the copy method above. This copies the information that has already been read in as well as performing the additional processing to interpret the fields that are necessary to for writing spreadsheets. The disadvantage of this read-optimized strategy is that we have two spreadsheets held in memory rather than just one, thus doubling the memory requirements. For this reason copying and modifying large spreadsheets can be expensive in terms of processing and memory.

 

意思是说。复制和修改优点是只需要将原文件通过一个复制方法生成就行。而缺点是。我们必须在内存中保存两份文件的内容。这样付出的代价是昂贵的。

 

 

好了。关于jxl的操作就到此为止。附件我会附上源代码。

 

 

 

  • jxl.zip (46.6 KB)
  • 下载次数: 59
1
3
分享到:
评论
1 楼 leo_soul 2015-07-29  
哥们,源码注释都是乱码。你用什么编码格式的?我试过bg2312 gbk big5 你确定你写的是中文注释??????

相关推荐

Global site tag (gtag.js) - Google Analytics