利用API后台导入excel数据入库
在实际应用中,数据的来源是多种多样的,可以是数据库中的已知数据,可以是以文件存在的单体数据等.假如我们的数据来源是来自于一个excel文件,那么我们如何来将里面的数据导入到数据库里面呢?
在润乾报表中提供了2种方式,第一种是通过展现报表模版,在页面中选择导入的excel,然后提交到数据库.另一种是后台利用API直接对excel文件进行操作,然后导入到数据库中.下面我们就来介绍一下第二种方式.
示例代码:
    
      //设置报表模版
      String AppPath = getServletContext().getRealPath(“/”);
      String reportFile = AppPath + “/reportFiles/testupdate.raq”;
     
      Context cxt = new Context();
      ReportDefine rd = null;
      //读取报表模版     
      try {
       rd = (ReportDefine) ReportUtils.read(reportFile);
      } catch (Exception exception) {
       exception.printStackTrace();
      }
      //加载引擎计算
      Engine engine = new Engine(rd, cxt);
      IReport iReport = engine.calc();
      //转为行式报表,因为只有行式报表才支持不定行导入数据
     RowReport rr = (RowReport)iReport;
      String did = rr.getDetailID( 1 ); //第几行是主扩展行
      
      SimpleDateFormat dateF = new SimpleDateFormat( FormatUtils.getDateFormat( Locale.getDefault() ) );
      SimpleDateFormat timeF = new SimpleDateFormat( FormatUtils.getTimeFormat( Locale.getDefault() ) );
      SimpleDateFormat datetimeF = new SimpleDateFormat( FormatUtils.getDatetimeFormat( Locale.getDefault() ) );
      
      try {
       ExcelImporter ei = new ExcelImporter(saveToFilePath);
       IReport excelReport = ei.getReport(0);
       RowReportSaver rowSaver = new RowReportSaver(rr, null, cxt);  //构造数据保存对象
        //读入excel文件及其数据
             for(int i=1;i<=excelReport.getRowCount();i++){  ////逐行逐列把excel数据写入填报表
             Area area = rr.insertDetail( did );  
             for(int j=1;j<=iReport.getColCount();j++){
              INormalCell iExcelCell=excelReport.getCell(i, (short)j); //取得excel单元格
                  
                  if( iExcelCell == null ) continue;
                  String svalue = “”;
                  Object value = iExcelCell.getValue();
                  if( value != null ) svalue = value.toString(); 
                 //执行保存方法 
                  rowSaver.setCellInputValue( area.getBeginRow(), (short)j, svalue, dateF, timeF, datetimeF );  
                
                        }
                        
                                             }  
             
             rowSaver.save(); //执行保存
            
     } catch (Exception e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
      }
此方法主要依托于报表模版中的更新属性设置来完成最后的数据保存入库,简单方便,如果脱离报表后台导入数据入库就会非常麻烦且不易复用.