2012-11-16 43 views
0

我正在使用poi-3.8-20120326.jar和Excel 2007,嘗試收集一個列表中的所有單元格值。Poi Formula評估錯誤

我正在使用公式進行日期增量操作。例如:=(i2+3)爲k2單元格。

,同時通過我的java代碼評估此公式返回#VALUE!i2是一個日期細胞。)

+1

你的問題是什麼:) – ajacian81

+0

確實你的問題是什麼,你可以發佈你的腳本... –

回答

1

沒有源很難猜測什麼是錯的,但我認爲這是兩件事情,你可能會忘記。

1)FormulaEvaluator

2)DataFormatter

看看例子。

import org.apache.poi.ss.usermodel.WorkbookFactory; 
import org.apache.poi.ss.usermodel.Workbook; 
import org.apache.poi.ss.usermodel.Sheet; 
import org.apache.poi.ss.usermodel.Row; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.DataFormatter; 
import org.apache.poi.ss.usermodel.FormulaEvaluator; 
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 

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

public class CellReader { 

    private Workbook workbook; 
    private DataFormatter formatter; 
    private FormulaEvaluator evaluator; 

    private void openWorkbook(String file) throws FileNotFoundException, 
      IOException, InvalidFormatException { 
     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(file); 

      workbook = WorkbookFactory.create(fis); 
      evaluator = workbook.getCreationHelper().createFormulaEvaluator(); 
      formatter = new DataFormatter(true); 
     } finally { 
      if (fis != null) { 
       fis.close(); 
      } 
     } 
    } 

    private void printXLSX() { 
     Sheet sheet = null; 
     Row row = null; 
     Cell cell = null; 
     int lastRowNum; 
     int lastCellNum; 
     sheet = workbook.getSheetAt(0); 

     lastRowNum = sheet.getLastRowNum(); 
     for (int j = 0; j <= lastRowNum; j++) { 
      row = sheet.getRow(j); 
      if (row == null) { 
       continue; 
      } 
      lastCellNum = row.getLastCellNum(); 
      for (int k = 0; k <= lastCellNum; k++) { 
       cell = row.getCell(k); 
       if (cell == null) { 
        continue; 
       } 
       if (cell.getCellType() != Cell.CELL_TYPE_FORMULA) { 
        System.out.println(formatter.formatCellValue(cell)); 
       } else { 
        System.out.println(formatter.formatCellValue(cell,evaluator)); 
       } 
      } 

     } 
    } 

    public static void main(String[] args) { 
     CellReader converter = null; 
     try { 
      converter = new CellReader(); 
      converter.openWorkbook("a.xlsx"); 
      converter.printXLSX(); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 
}