2013-06-24 220 views
0

我寫了一個用於下載excel文件的代碼。從數據庫派生的文件內容。代碼在本地機器上工作,但部署在服務器上。 Excel文件在下載時被破壞。我無法在我的代碼中找到問題。請幫我擺脫這個問題。第一種方法導出excel和第二種方法寫入excelsheet中的內容。第二種方法是用第一種方法調用的。使用java從服務器下載Excel文件時出現損壞

public static void doGetExportException(String sheetId, ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws ServletException, IOException 
{ 


    HttpServletResponse response = PortalUtil.getHttpServletResponse(resourceResponse); 
    try 
    { 
     long maxSheetId = Long.parseLong(sheetId); 
     System.out.println("maxSheetId="+maxSheetId); 
     List<Customer_Exception> lstCustomer_Exceptions =UploadExcelUtil.getCustomerExceptions(maxSheetId); 

     XSSFWorkbook outPutSheet= writeExcelsheet(lstCustomer_Exceptions); 

     ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); 
     outPutSheet.write(outByteStream); 
     byte [] outArray = outByteStream.toByteArray(); 

     String fileName = "Download_"+new Date(new java.util.Date().getTime())+".xlsx"; 
     response.setContentType("application/ms-excel; charset=UTF-8"); 
     response.setContentLength(outArray.length); 
     response.setHeader("Expires:", "0"); 
     response.addHeader(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate"); 
     response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName); 
     response.addHeader(HttpHeaders.CONTENT_ENCODING, "Binary"); 
     OutputStream outStream = response.getOutputStream(); 
     outStream.write(outArray); 
     outStream.flush(); 
     outStream.close(); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
} 

private static XSSFWorkbook writeExcelsheet(List<Customer_Exception> lstCustomer_Exceptions) { 
    XSSFWorkbook workbook = new XSSFWorkbook(); 
    XSSFSheet sheet = workbook.createSheet("Exceptions"); 

    CellStyle styleHeader = workbook.createCellStyle(); 
    XSSFFont fontHeader = workbook.createFont(); 
    XSSFColor color = new XSSFColor(Color.BLACK); 
    fontHeader.setColor(color); 
    fontHeader.setBold(true); 
    fontHeader.setFontHeight(13); 
    styleHeader.setFont(fontHeader); 
    sheet.createFreezePane(0, 1); 
    CellStyle styleData = workbook.createCellStyle(); 
    XSSFFont fontData = workbook.createFont(); 
    fontData.setColor(color); 
    fontData.setFontHeight(12); 
    styleData.setFont(fontData); 

    int rownum = 0; 
    XSSFRow rowHeader = sheet.createRow(rownum++); 
    List<String> lstCellHeaders =getCellHeaders(); 
    int cellnum = 0; 
    for(String cellHeader:lstCellHeaders){ 
     XSSFCell cell = rowHeader.createCell(cellnum++); 
     cell.setCellStyle(styleHeader); 
     cell.setCellValue((String)cellHeader); 

    } 



    for (Customer_Exception customer_Exception:lstCustomer_Exceptions) { 
     List<String> lstCellValues =getCellValues(customer_Exception); 
     XSSFRow rowData = sheet.createRow(rownum++); 

     cellnum = 0; 
     for(String cellValue:lstCellValues){ 
      XSSFCell cell = rowData.createCell(cellnum++); 
      cell.setCellStyle(styleData); 
      cell.setCellValue((String)cellValue); 

     } 
    } 
    return workbook; 
} 
+1

在服務器/客戶端發生任何異常?捕獲所有異常是一種不好的做法,如果您在請求處理過程中無法處理/從錯誤中恢復,則應該重新拋出它(可能被打包)或使用適當的http代碼(例如500)進行響應。 – Pyranja

+0

我已經添加catch來找出下載過程中的問題,並希望向用戶顯示適當的massege。 – user2515040

+0

我已經得到了解決方案。我已經刪除了「response.addHeader(HttpHeaders.CONTENT_ENCODING,」Binary「);」那麼它的工作正常 – user2515040

回答

0

對於你應該使用的ContentType的.xlsx: 「應用程序/ vnd.openxmlformats-officedocument.spreadsheetml.sheet」。 這解決了我的問題。

0

即使我被這個問題困住了大約1周。最後,我解決了這個問題,並得到了一個excel輸出,而不會被使用下面的代碼損壞。

我做了一個maven項目。

添加超級CSV睿以下依賴»2.4.0在 pom.xml文件

<!-- https://mvnrepository.com/artifact/net.sf.supercsv/super-csv --> 
<dependency> 
    <groupId>net.sf.supercsv</groupId> 
    <artifactId>super-csv</artifactId> 
    <version>2.4.0</version> 
</dependency> 

現在使用下面的代碼爲你的控制器類

CSVFileDownloadController .java

import java.io.IOException; 
import java.util.Arrays; 
import java.util.List; 

import javax.servlet.http.HttpServletResponse; 

import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.supercsv.io.CsvBeanWriter; 
import org.supercsv.io.ICsvBeanWriter; 
import org.supercsv.prefs.CsvPreference; 

import com.rapidvalue.master.employee.vo.Book; 

@Controller 
public class CSVFileDownloadController { 
     @RequestMapping(value = "/downloadCSV") 
     public void downloadCSV(HttpServletResponse response) throws IOException { 

      String csvFileName = "books.csv"; 

      response.setContentType("text/csv"); 

      // creates mock data 
      String headerKey = "Content-Disposition"; 
      String headerValue = String.format("attachment; filename=\"%s\"", 
        csvFileName); 
      response.setHeader(headerKey, headerValue); 

      Book book1 = new Book("Effective Java", "Java Best Practices", 
        "Joshua Bloch", "Addision-Wesley", "0321356683", "05/08/2008", 
        38); 

      Book book2 = new Book("Head First Java", "Java for Beginners", 
        "Kathy Sierra & Bert Bates", "O'Reilly Media", "0321356683", 
        "02/09/2005", 30); 

      Book book3 = new Book("Thinking in Java", "Java Core In-depth", 
        "Bruce Eckel", "Prentice Hall", "0131872486", "02/26/2006", 45); 

      Book book4 = new Book("Java Generics and Collections", 
        "Comprehensive guide to generics and collections", 
        "Naftalin & Philip Wadler", "O'Reilly Media", "0596527756", 
        "10/24/2006", 27); 

      List<Book> listBooks = Arrays.asList(book1, book2, book3, book4); 

      // uses the Super CSV API to generate CSV data from the model data 
      ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(), 
        CsvPreference.STANDARD_PREFERENCE); 

      String[] header = { "Title", "Description", "Author", "Publisher", 
        "isbn", "PublishedDate", "Price" }; 

      csvWriter.writeHeader(header); 

      for (Book aBook : listBooks) { 
       csvWriter.write(aBook, header); 
      } 

      csvWriter.close(); 
     } 
    } 

以此作爲你的模型數據類

Book.java

public class Book { 
    private String title; 
    private String description; 
    private String author; 
    private String publisher; 
    private String isbn; 
    private String publishedDate; 
    private float price; 

    public Book() { 
    } 

    public Book(String title, String description, String author, String publisher, 
      String isbn, String publishedDate, float price) { 
     this.title = title; 
     this.description = description; 
     this.author = author; 
     this.publisher = publisher; 
     this.isbn = isbn; 
     this.publishedDate = publishedDate; 
     this.price = price; 
    } 

    // getters and setters... 
} 

現在運行在服務器上的代碼。在瀏覽器中打開網址。您的文件將被下載沒有任何問題。希望這會有所幫助! :)