您的位置:首页 > 其它

使用POI处理Excel中公式不能自动计算出来的问题

2008-03-19 22:53 1191 查看
使用POI导入了拥有公式的Excel模板后,发现其中原有公式单元格计算出来的值不能正常显示出来,需要重新刷新该公式后方可正常得出计算结果.

针对此问题,写了一个测试,代码如下:

package cn.fory.formula;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
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.poifs.filesystem.POIFSFileSystem;

public class TestFormula {
 /**
  * 测试POI处理公式
  *
  * 问题描述:通过POI导入的数据后,引用导入数据的原有公式单元格不能显示出来,需要重新定位到公式单元
  *     格然后重新转入公式才行成得结果
  *
  * 解决办法:重新对公式单元格设置公式
  *
  * 相关文件:test.xls文件中手工设置单元格B2=C2+D2
  *
  */
 public static void main(String[] args) throws FileNotFoundException {

  POIFSFileSystem fs;

  try {
   fs = new POIFSFileSystem(new FileInputStream("test.xls"));
   HSSFWorkbook wb = new HSSFWorkbook(fs);
   HSSFSheet sheet = wb.getSheet("Sheet1");
   HSSFRow row = sheet.getRow((short) 1);

   HSSFCell cell = row.getCell((short) 2);
   cell.setCellValue((short) 5);

   cell = row.getCell((short) 3);
   cell.setCellValue((short) 40);

   HSSFCell cell1 = row.getCell((short)1);
   if (HSSFCell.CELL_TYPE_FORMULA == cell1.getCellType()) {
    //取得公式单元格的公式,重新设置
    cell1.setCellFormula(cell1.getCellFormula());
   }

   FileOutputStream fileOut = new FileOutputStream("test.xls");

   wb.write(fileOut);
   fileOut.close();

  } catch (IOException e) {   
   e.printStackTrace();
  }
 }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息