我使用Apache-POI "XSSF和SAX事件API“导入Excel文件。
我正在使用Apache-POI解析原始值,我想问一下,如何才能像Excel-GUI对Cell-Editor所做的那样对这些原始值进行舍入。下面的例子说明了这个问题:
Raw: 1.9210999999999999E-2 (value is stored like this in xlsx-file)
Edit: 1.9211% (user sees this value in excel cell-editor)
View: 1.92% (user sees this value in excel grid-overview)
Format: 0.00% (the cell-style)Excel如何将原始值读取到编辑值?Excel如何知道它需要舍入到小数点分隔符后的4位小数。Apache POI如何帮助我做同样的事情,以便我还可以在Excel-Import中使用Edit-Value (而不是View-Value)?
我见过一个类似的标签,介绍了Excel是如何做到这一点的:How does Excel successfully Rounds Floating numbers even though they are imprecise?。
在这张票据中,我想问,Apache POI如何帮助我,这样我就不需要在这里重新发明轮子,并实现Excels算法。
发布于 2018-02-21 00:48:00
Excel根据IEEE754规范获取双精度值,然后四舍五入到15位有效数字,然后在工作表中显示。
要做同样的事情,可以使用根据15位精度的MathContext设置四舍五入的BigDecimal。
import java.math.BigDecimal;
import java.math.MathContext;
class ReadLongNumbersAsExcel {
public static void main(String[] args) throws Exception{
String v = "1.921099999999999E-2";
double d = Double.parseDouble(v);
System.out.println("raw: " + v);
System.out.println("double: " + d);
BigDecimal bd = new BigDecimal(d);
v = bd.round(new MathContext(15)).toPlainString();
System.out.println("like Excel: " + v);
}
}%是一个特例,因为在这种情况下,Excel显示的不是真正存储的值,而是该值乘以100,然后是"%“。所以,如果你想做同样的事情,那就做同样的事情。在将原始值四舍五入为15位有效数字后,乘以100并附加一个"%“。
但是,如果只需要像在Excel中那样获取格式化的值,那么请参阅How to check a number in a string contains a date and exponential numbers while parsing excel file using apache event model in java
https://stackoverflow.com/questions/48889900
复制相似问题