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

来源:互联网 发布:spss数据统计与分析pdf 编辑:程序博客网 时间:2024/06/11 05:45


问题描述

润乾报表能够将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(); //计算报表
————————————————-

有的时候对Excel中文本类型的单元格使用getDispValue()得到的是null,所以有如下判断
if(iExcelCell.getDispValue()!=null){ iCell.getInputProperty().setInputValue(iExcelCell.getDispValue());
}else{ iCell.getInputProperty().setInputValue(iExcelCell.getValue());
}

运行该程序,结果如下图所示,数据精度完整显示。

0 0