2014-04-28 59 views
1

我有一个web应用程序,其中我有excel文件(.xls)下载选项。现在我必须在.xlsx中提供该功能使用POI从.xls升级到.xlsx

我正在尝试使用POI Jar。当我尝试这样做,作为一个独立的应用程序,它工作正常,但是当我试图将其集成到一个web应用程序,我得到一个错误

Excel中发现在FILENAME.xlsx无法读取内容。你想恢复这个工作簿的内容吗?
如果您信任此工作簿的来源,请点击是!

XSSFWorkbook w = FileName.createExcelWorkbookPosition(
     request.getParameter("BSNS_DT")); 
response.setContentType(
     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
response.setHeader("Content-Disposition","attachment;filename=filename.xlsx"); 
w.write(response.getOutputStream()); 

这里的Java代码,我创建电子表格:

public static XSSFWorkbook createExcelWorkbookPosition(String BsnsDate) 
    throws Exception 
{ 
    FileOutputStream out = new FileOutputStream("workbook.xlsx"); 

    // create a new workbook 
    XSSFWorkbook wb = new XSSFWorkbook(); 
    // create a new sheet 
    XSSFSheet s = wb.createSheet(); 
    // declare a row object reference 
    XSSFRow r = null; 
    // declare a cell object reference 
    XSSFCell c = null; 

    // header row and columns 
    r = s.createRow(0); 
    c = r.createCell(0); 
    c.setCellValue("Business Date");  
    //c.setCellStyle(cs); 
    c = r.createCell(1); 
    c.setCellValue("Account No"); 

    try { 
     wb.write(out); 
     out.close(); 
     System.out.println("File writed"); 
    } catch (Exception e) { 
     System.out.println("Error"); 
     System.out.println(e); 
    } 
    return wb; 
} 

任何人都可以请帮助?对不起,英文不好!谢谢。

+0

你能分享你用它来创建Excel工作簿中的代码? – Priyesh

+0

你可以发布一些代码片段以确保excel正确生成吗?你只改变了文件扩展名吗?也改变了一代? – zeppaman

+0

选中此链接。 http://answers.microsoft.com/en-us/office/forum/office_2007-excel/excel-found-unreadable-content/d5c54cc7-6290-4f55-86ac-21a65f9bb807。可能有帮助。 – Priyesh

回答

4

我有一个很相似的问题,请看看Forcing the browser to download a docx file in JAVA generates a corrupted document。重点是添加响应的Content-Length标头。

尽量让createExcelWorkbookPosition返回文件,而不是XSSFWorkbook

public static File createExcelWorkbookPosition(String BsnsDate) throws Exception { 
    File file = new File("workbook.xlsx"); 
    FileOutputStream out = new FileOutputStream(file); 
    // ... 
    return file; 
} 

然后:

File file = FileName.createExcelWorkbookPosition(request.getParameter("BSNS_DT")); 
// ... 
response.setContentLength((int) file.length());  

InputStream in = new FileInputStream(file); 
OutputStream out = response.getOutputStream(); 
byte[] buffer = new byte[1024]; 
int len; 
while ((len = in.read(buffer)) != -1) { 
    out.write(buffer, 0, len); 
} 
// if using Apache IO, the above code can be simplified to IOUtils.copy(in, out); 
// if using Guava, Files.copy(file, out); 

// don't forget to close your streams and flush the response buffer 
+0

谢谢它的工作就像一个魅力。可以请告诉我是有必要初始化1024字节数组。如果我有太多的数据。会导致我一个问题。谢谢很多For你的帮助 。 – crazyStart

+2

@crazyStart这只是缓冲区的大小。有关更多详细信息,请参阅http://stackoverflow.com/q/8748960/1225328。如果这个答案适合你的需求,不要忘记[接受](http://meta.stackoverflow.com/a/5235/186921)它;) – sp00m