【问题标题】:receive an excel file as response in javascript from a Rest service从 Rest 服务接收 excel 文件作为 javascript 响应
【发布时间】:2023-03-10 22:52:01
【问题描述】:

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

网络服务代码:

  @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文件。这是我编写的第一个 Web 服务请求/响应调用。因此,请帮助您了解如何读取服务器的响应。

【问题讨论】:

  • 您的代码看起来杂乱无章、注释过多且难以阅读。
  • 嗨,kolossus。我的问题是如何处理从 Java 端返回的响应对象。在 javascript 中,我们应该如何接收响应,并在从服务器返回后自动下载/显示 SaveAs,或者让它下载页面的代码是什么

标签: java javascript excel web-services rest


【解决方案1】:

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

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

2.在Response header中设置“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

【讨论】:

  • 您应该添加链接中引用的一些内容,以防将来不再可用。
猜你喜欢
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 2015-09-27
相关资源
最近更新 更多