POI讀入Excel用String讀取數值類型失真問題(精度丟失)


問題:POI讀取Excel數值單元格時,讀取的小數數值與真實值不一致

話不多說,直接上代碼!

public static String getRealStringValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}else {
final CellType cellType = cell.getCellType();
if (CellType.NUMERIC.equals(cellType)) {
cellValue = DoubleUtils.realStringValueOfDouble(cell.getNumericCellValue());
} else {
cell.setCellType(CellType.STRING);
cellValue = cell.getStringCellValue();
}
return cellValue;
}
}

public class DoubleUtils {

private DoubleUtils() {
}

public static String realStringValueOfDouble(Double d) {
String doubleStr = d.toString();
boolean b = doubleStr.contains("E");
int indexOfPoint = doubleStr.indexOf('.');
if (b) {
int indexOfE = doubleStr.indexOf('E');
BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint + BigInteger.ONE.intValue(), indexOfE));
int pow = Integer.parseInt(doubleStr.substring(indexOfE + BigInteger.ONE.intValue()));
int xsLen = xs.toByteArray().length;
int scale = xsLen - pow > 0 ? xsLen - pow : 0;
final String format = "%." + scale + "f";
doubleStr = String.format(format, d);
} else {
java.util.regex.Pattern p = Pattern.compile(".0$");
java.util.regex.Matcher m = p.matcher(doubleStr);
if (m.find()) {
doubleStr = doubleStr.replace(".0", "");
}
}
return doubleStr;
}
}




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM