从Rest服务接收一个excel文件作为javascript响应

时间:2014-02-18 22:45:30

标签: java javascript excel web-services rest

我正在通过javascript调用webservice调用来获取excel文件作为来自服务器的java appl的响应。我有点担心如何获得响应并访问它。 在webservice代码中 - 我从列表中获取数据(大量数据超过90000条记录)并将其写入excel表并将excel文件作为响应发送(我不确定代码是否正确 - 我测试了它并且没有例外但不确定逻辑)然后 Javascript代码 - submitReport方法调用Rest webservice - 如果响应是null throw错误,我的问题就在这里。我不知道如何从响应中读取/下载数据。请给我一些建议或示例代码以实现我的目标。

网络服务代码:

  @POST   
    @Path("/report")   
    @Consumes(MediaType.MULTIPART_FORM_DATA)   
    @Produces("application/vnd.ms-excel")   
    public Response getReportData(@Context HttpServletRequest request,   
      @FormDataParam("fromTimeStamp") String fromTimeStamp, @FormDataParam("toTimeStamp") String toTimeStamp) {      
    EOServiceResult<List<TagDataPoint>> result = new EOServiceResult<List<TagDataPoint>>();    
    List<TagDataPoint> listTotalResult = repo.getReportData(fromTimeStamp, toTimeStamp);//This method returns lots of data more than 90000 records.   
    //Blank workbook   
     final XSSFWorkbook workbook = new XSSFWorkbook();    
          //Create a blank sheet   
           final XSSFSheet sheet = workbook.createSheet("Report");   
     //This data needs to be written (Object[])    
            Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();    
            data.put(1, new Object[] {"Historian Tag", "Quality", "Value", "Timestamp"});  
            int i = 2;   
            for(TagDataPoint tagData : listTotalResult){   
                data.put(i, new Object[] {tagData.getTagname(), tagData.getQuality(), tagData.getValue(), tagData.getTimestamp()});   
                 i++;   
            }  
         //Iterate over data and write to sheet   
            Set<Integer> keyset = data.keySet();   
        int rownum = 0;
            for (Integer key : keyset)   
        {   
            Row row = sheet.createRow(rownum++);    
            Object [] objArr = data.get(key);   
            int cellnum = 0;   
            for (Object obj : objArr)    
            {    
               Cell cell = row.createCell(cellnum++);   
               if(obj instanceof String)    
                    cell.setCellValue((String)obj);    
                else if(obj instanceof Integer)   
                    cell.setCellValue((Integer)obj);   
                else if(obj instanceof Date)    
                    cell.setCellValue((Date)obj);    
            }   
        }    
        ResponseBuilder response = null;   
        try{    
        File file = new File("first_excel.xlsx");     
        FileOutputStream out = new FileOutputStream(file);     
        workbook.write(out);    
        out.close();    
        response = Response.ok((Object) file);    
        }catch(Exception e){    
            e.printStackTrace();   
        }    
       //  ResponseBuilder     
     response.header("Content-Disposition", "attachment; filename=\"test_excel_file.xls\"");      
        return response.build();      
        }    
    **Javascript code:**      
     databaseFactory..getReportResponse: function( fromTimeStamp, toTimeStamp ){   
        var blankFormData =  new FormData();   
          blankFormData.append("fromTimeStamp", fromTimeStamp);   
          blankFormData.append("toTimeStamp", toTimeStamp);   
          var promise = $http(   
             {   
                "method":"POST",    
                "url":SERVER+'/EfficiencyMap/api/v1/datamodel/report' ,    
                "data":blankFormData,   
                "timeout":100000,   
                headers: { 'Content-Type' :  undefined},    
                transformRequest : angular.identity   
             })    
             .success(function(response){   
                return response;   
             });   
          return promise;  
           }   
    **//Actual method after the response**     
    $scope.submitReport = function(fromTimeStamp, toTimeStamp){     
       databaseFactory.getReportResponse(fromTimeStamp,     toTimeStamp).success(function(response){   
            if(response == null){    
               $scope.message = DATA_NOT_AVAILABLE + fromTimeStamp +  " and " + toTimeStamp;   
                return;   
            }  
     **// So what should be done here any suggestions please    
            // I don't understand the response here. How should I download the file here**          
    };    

我需要在前端自动下载响应excel文件。这是我写的第一个webservice请求/响应调用。因此,请帮助您了解如何从服务器读取响应。

1 个答案:

答案 0 :(得分:1)

在JAX-RS中,对于excel文件,使用@Produces(&#34; application / vnd.ms-excel&#34;)注释方法:

1.在服务方法上放置@Produces(“application / vnd.ms-excel”)。

2.在Response标题中设置“Content-Disposition”以提示下载框。

代码:

import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

@Path("/excel")
public class ExcelService {

    private static final String FILE_PATH = "c:\\excel-file.xls";

    @GET
    @Path("/get")
    @Produces("application/vnd.ms-excel")
    public Response getFile() {

        File file = new File(FILE_PATH);

        ResponseBuilder response = Response.ok((Object) file);
        response.header("Content-Disposition",
            "attachment; filename=new-excel-file.xls");
        return response.build();

    }

}

我不知道它是否仍然有用,不过你是can see