如何在客户端创build一个Excel电子表格

我正在创build一个Web应用程序,我想在结果中显示一个Excel图标。 当用户点击图标时,应该在客户机上打开一个电子表格,其中有一些数据由服务器发送(客户端将安装excel)。

我写了一些代码来从web服务在本地机器上创buildexcel。

public class App { public static void main( String[] args ) { try { URL oracle = new URL("http://someService.com"); URLConnection yc =null; yc = oracle.openConnection(); //Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Sample sheet"); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; int rowNum =0; while ((inputLine = in.readLine()) != null) { Row row = sheet.createRow(rowNum++); String[] coloumns = inputLine.split("\t"); int cellNum =0; for(String coloumn: coloumns){ coloumn. Cell cell = row.createCell(cellNum++); cell.setCellValue(coloumn); } System.out.println(inputLine); } in.close(); FileOutputStream out = new FileOutputStream(new File("C:\\libraries\\new.xls")); workbook.write(out); out.close(); System.out.println("Excel written successfully.."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

这工作正常。 它所做的只是读取来自Web服务的数据,并在C:\ libraries \ new.xls的机器中创build电子表格。

现在,如果我在Web应用程序,我想打开客户机上的电子表格。 我不必保存表格。 只需打开数据。

如何使用Web服务中的这些数据在客户机上打开电子表格?

编辑

这是我的新服务器代码:

 @RequestMapping(value = "/Excel") public void getFile(HttpServletResponse response){ OutputStream out =null; try { out = response.getOutputStream(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } response.setContentType("application/x-ms-excel"); try { URL oracle = new URL("http://someService.com"); URLConnection yc =null; yc = oracle.openConnection(); //Get the workbook instance for XLS file IOUtils.copy(yc.getInputStream(),out); out.flush(); System.out.println("Excel written successfully.."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

所以现在我跑了networking应用程序,什么都没有发生? 我应该做一些前端调用这个stream。

你可以在Spring MVC控制器里面做这样的事情,把文件发送到客户端的计算机上:

 @RequestMapping(value = "/myexcelreport") public void getFile( HttpServletResponse response) { OutputStream out=response.getOutputStream(); response.setContentType("application/x-ms-excel"); ... Same code a before, just use out instead of a FileOutputStream , and don't close out. out.flush(); }