前段时间项目有需要要求读取excel中的数据,我就想到了用jxl类库来实现,jxl用起来挺简单的,原来也用过,我取值的时候是这样写的
sheet.getCell(17,i).getContents()
在根据得到的值来转换为各种类型,但是我有几个表格中的数据值是小数点后五位,怎么取都得到的是三位小数,网上找了一下资料说,excel的表格设置为文本框,还是一样的效果,没办法就看了下jxl这个以部分的源码
/**
* The number format
*/
private NumberFormat format;
/**
* The string format for the double value
*/
private static final DecimalFormat defaultFormat =
new DecimalFormat("#.###");
/**
* Constructs this object from the raw data
*
* @param t the raw data
* @param fr the available formats
* @param si the sheet
*/
public NumberRecord(Record t, FormattingRecords fr, SheetImpl si)
{
super(t, fr, si);
byte[] data = getRecord().getData();
value = DoubleHelper.getIEEEDouble(data, 6);
// Now get the number format
format = fr.getNumberFormat(getXFIndex());
if (format == null)
{
format = defaultFormat;
}
}
/**
* Accessor for the value
*
* @return the value
*/
public double getValue()
{
return value;
}
/**
* Returns the contents of this cell as a string
*
* @return the value formatted into a string
*/
public String getContents()
{
return format.format(value);
}
在源码中你会看到对于double类型的数据,当你用getContents()这个方法的时候,jxl会默认解析为三位小数的数据,找到原因就好解决了
NumberCell cell = (NumberCell) zyysSheet.getCell(18,i);
fzwz = cell.getValue();
我们可以把对于是数据类型的数据强转为NumberCell的其实也就是NumberRecord这个类,然后在去直接取值就好了