0

I am calling a webservice call from javascript to get an excel file as response from java appl from server. I am kind of stuck how to get the response and access it. Here in the webservice code- I am getting data from a list(lots of data more than 90000 records) and writing it to an excel sheet and sending the excel file as response(I am not sure whether the code is right-I tested it and no exceptions but not sure on logic) and then the Javascript code- submitReport method calls the Rest webservice-if response is null throw error and the problem for me is here. I dont know how to read/download data from the response. Please give me some suggestions or sample code to achieve my goal.

Webservice code:

  @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**          
    };    

I need to automatically download the response excel file in the frontend. This is my first webservice request/response calls I wrote. So please help in how to read the response from the server.

2
  • Your code looks disorganized, over-commented and hard to read. Commented Feb 19, 2014 at 21:09
  • hi kolossus. my issue is how to handle the response object that is returned from the Java side. In javascript how should we receive the response and does it automatically download/show SaveAs after returnign from server or what is the code to make it download the page Commented Feb 19, 2014 at 22:33

1 Answer 1

1

In JAX-RS, for excel file, annotate the method with @Produces("application/vnd.ms-excel") :

1.Put @Produces(“application/vnd.ms-excel”) on service method.

2.Set “Content-Disposition” in Response header to prompt a download box.

The code:

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();

    }

}

I do not know if it is still useful, however you can see

Sign up to request clarification or add additional context in comments.

1 Comment

You shoud add some of the content referenced in the link, just in case it is no longer available in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.