搜索文章

推荐内容

快逸做的更好

产品优势

您的位置: 首页 > 报表技术分享 > Excel保存到数据库时数据精度的处理

Excel保存到数据库时数据精度的处理

问题描述

报表工具提供了将Excel保存到数据库的相应接口,方便了我们将Excel中数据导入数据库。但是应用中我们发现,对于Excel中数值型数据并且其设置了小数位数(如2位)时,导入数据库时会精度丢失。

数据库中数据

我们可以看到,小数位数后面的0都不见了。

问题出现原因

当我们使用ExcelImporter读入Excel并使用getReport()方法得到其iRepor对象时,报表并未经过运算。而报表引擎只有经过运算后才能识别Excel中的数据格式并保留相应精度。

所以我们必须使得读入Excel的报表进行相应的运算处理。

解决方法

我们来看一下具体的实现源码(主要部分)

代码段一:

public void saveFromExcel(String reportFile, String excelFile, int sheetNum)

throws Exception {

IReport report = calcReport(reportFile);

ReportDefine2 excelReport = (ReportDefine2) excelToReport(excelFile,sheetNum);

Engine engine = new Engine(excelReport, cxt);

IReport iReport = engine.calc();

System.out.println(“Excel中数据为:);

for(int i=1;i<=report.getRowCount();i++){

for(int j=1;j<=report.getColCount();j++){

INormalCell iCell=report.getCell(i, (short)j);

INormalCell iExcelCell=iReport.getCell(i, (short)j);

if(iCell.getInputProperty()!=null){

if(iExcelCell.getDispValue()!=null){

System.out.print(iExcelCell.getDispValue()+” “);

iCell.getInputProperty().setInputValue(iExcelCell.getDispValue());

}else{

System.out.print(iExcelCell.getValue()+” “);

iCell.getInputProperty().setInputValue(iExcelCell.getValue());

}

}else{

InputProperty ip = new InputProperty();

ip.setInputValue(iExcelCell.getValue());

iCell.setInputProperty( ip );

}

}

System.out.println();

}

DataSaver dsave = new DataSaver((ExtCellSet)report,null,cxt);

dsave.save();

}

代码段二:

private IReport excelToReport(String excelFile, int sheetNum)

throws Exception {

ExcelImporter ei = new ExcelImporter(excelFile);

return ei.getReport(sheetNum);

}

请注意代码段一中的

————————————————-

ReportDefine2 excelReport = (ReportDefine2) excelToReport(excelFile,sheetNum); //将读入的iReport对象强制转化成ReportDefine2对象

Engine engine = new Engine(excelReport, cxt);

IReport iReport = engine.calc(); //计算报表

————————————————-

我们要首先使用getDispValue()得到值,但是有的时候对于Excel中文本类型的单元格得到的是null,所以有如下判断

if(iExcelCell.getDispValue()!=null){ iCell.getInputProperty().setInputValue(iExcelCell.getDispValue());

}else{ iCell.getInputProperty().setInputValue(iExcelCell.getValue());

}

运行该程序,结果如下图示,其中的数据精度保存完好。

本文标签: