After using poi to import an Excel template with a formula, it is found that the value calculated from the original formula cell cannot be displayed normally. You need to refresh the formula before obtaining the calculation result.
To solve this problem, I wrote a Test Code as follows:
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 {
/**
* Test the poi Processing Formula.
*
* Problem description: After data is imported through poi, the original formula cells that reference the imported data cannot be displayed. You need to locate the formula unit again.
* The result is obtained after the formula is transferred again.
*
* Solution: Set the formula again for the formula cell.
*
* Related Files: manually set cell b2 = C2 + D2 in the test.xls File
*
*/
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 ()){
// Obtain the formula cell formula and reset it.
Cell1.setcellformula (cell1.getcellformula ());
}
Fileoutputstream fileout = new fileoutputstream ("test.xls ");
WB. Write (fileout );
Fileout. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}