2013-04-04 60 views
1

我找不出什麼問題。我嘗試過,但錯誤仍然存​​在。在java中寫入excel時出現錯誤

我的計劃是要導出到Excel中,我使用Apache POI API。

以下是我的代碼。編輯:

public void exportToExcel(ValueObjectList columnBody, String pageDef, ValueObject vo){ 
    try { 
    HttpServletResponse response = vo.getResponse(); 

    SimpleDateFormat sd = new SimpleDateFormat("ddMMyy"); 
    Date dt = new Date(); 
    response.setContentType("application/vnd.ms-excel"); 
    if(pageDef == "promo" || pageDef.equals("promo")) 
     response.setHeader("Content-Disposition", "attachment; filename=PROMO-" + sd.format(dt) + ".xls"); 
    else if(pageDef == "incomplete" || pageDef.equals("incomplete")) 
     response.setHeader("Content-Disposition", "attachment; filename=INCOM-" + sd.format(dt) + ".xls"); 
    else 
     response.setHeader("Content-Disposition", "attachment; filename=ST-" + sd.format(dt) + ".xls"); 


    // create a small spreadsheet 
    HSSFWorkbook wb = new HSSFWorkbook(); 
    HSSFSheet sheet = wb.createSheet(); 

    HSSFRow row = null; 
    HSSFCell cell = null; 

    //set default font properties 
    //font family: Arial 
    //font weight: bold 
    Font headerFont = wb.createFont(); 
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); 

    headerFont.setFontHeightInPoints((short)14); 

    //Cell Style for header 
    CellStyle csHeader = wb.createCellStyle(); 
    csHeader.setFont(headerFont); 
    csHeader.setBorderBottom(csHeader.BORDER_THICK); 
    csHeader.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); 
    csHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
    csHeader.setWrapText(true); 

    //Cell Style for body 
    CellStyle csBody = wb.createCellStyle(); 
    csBody.setWrapText(true); 
    csBody.setAlignment(HSSFCellStyle.ALIGN_CENTER); 


    String[] columnHeader = ((ValueObject)columnBody.get(0)).toKeyArray(); 
    //System.out.println("Header Length: " + columnHeader.length); 

    row = sheet.createRow(0); 
    cell = row.createCell(0); 
    cell.setCellValue("No"); 
    cell.setCellStyle(csHeader); 

    for(int h = 0; h < columnHeader.length; h++){ 
     cell = row.createCell(h+1); 
     cell.setCellValue(columnHeader[h]); 
     cell.setCellStyle(csHeader); 
     sheet.autoSizeColumn(h+1); 
     //sheet.setColumnWidth(h, 2000); 
    } 

    //System.out.println("header key : " + columnHeader[2]); 
    //System.out.println("header value : " + testobj.get(testobj.toKeyArray()[2])); 

    for(int i = 0; i < columnBody.size(); i++){ 
     row = sheet.createRow(i+1); 
     cell = row.createCell(0); 
     cell.setCellValue(i+1); 
     cell.setCellStyle(csBody); 
     ValueObject column = (ValueObject)columnBody.get(i); 
     for(int j = 0; j < column.size(); j++){ 
      cell = row.createCell(j+1); 
      cell.setCellValue(column.get(column.toKeyArray()[j])); 
      cell.setCellStyle(csBody); 
      sheet.autoSizeColumn(j+1); 
     } 
    } 


    /* 
    // write it as an excel attachment 
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); 
    wb.write(outByteStream); 
    byte [] outArray = outByteStream.toByteArray(); 
    response.setContentType("application/ms-excel"); 
    response.setContentLength(outArray.length); 
    response.setHeader("Expires:", "0"); // eliminates browser caching 
    if(pageDef == "promo" || pageDef.equals("promo")) 
     response.setHeader("Content-Disposition", "attachment; filename=PROMO-" + sd.format(dt) + ".xls"); 
    else if(pageDef == "incomplete" || pageDef.equals("incomplete")) 
     response.setHeader("Content-Disposition", "attachment; filename=INCOM-" + sd.format(dt) + ".xls"); 
    else 
     response.setHeader("Content-Disposition", "attachment; filename=ST-" + sd.format(dt) + ".xls"); 

    OutputStream outStream = response.getOutputStream(); 
    outStream.write(outArray); 
    outStream.flush(); 
    */ 


    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(wb.getBytes().length); 
    wb.write(outByteStream); 


    } catch (Exception e) { 
     log.error(e); 
     e.printStackTrace(); 
    } 
} 

我試圖在谷歌衝浪,並試圖解決,但不好。

首先,我在jsp中製成這些代碼。

當我瀏覽谷歌,人們說我已經讓我感動與Servlet,但還是得到了錯誤的servlet來使用。

英語不是我的母語。對不起,如果我輸入錯誤。

在此先感謝。

+0

該錯誤看起來與HSSF和POI無關。 「File」/common/err/errorPage.jsp「找不到」 – 2013-04-04 02:12:36

+0

@JimGarrison,當我包含errorPage.jsp時,它顯示「java.lang.IllegalStateException:getOutputStream()已被調用此響應」 – Raymond 2013-04-04 02:18:02

+0

你是否多次調用'response.getOutputStream()'? – 2013-04-04 02:23:23

回答

1

我猜你的錯誤與此位的代碼(而不是Apache POI API):

OutputStream outStream = response.getOutputStream(); 
outStream.write(outArray); 
outStream.flush(); 
outStream.close(); 

因爲你沖洗並在你的servlet關閉輸出流,任何試圖寫入響應返回給客戶端之前的輸出流將導致引發IllegalStateException。 通常最好把flush()和close()留給servletcontainer,除非你真的知道你在做什麼。
嘗試刪除flush()和close(),並檢查其他servlet是否正在做同樣的事情。

+0

我刪除並測試過,但它仍然有錯誤。 – Raymond 2013-04-04 03:21:55

+0

我愛,當我找到舊的解決方案,只是工作。試圖弄清楚這個簡單的一個小時,我一直在搔着疲憊的腦袋。爲我工作很好。 :) – SiggeLund 2016-10-06 21:59:52

0

java.lang.IllegalStateException: getOutputStream() has already been called for this response

是因爲這些代碼

// write it as an excel attachment 
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); 
    wb.write(outByteStream); // This writes workbook to put put stream 

    // Perform these before wb.write(outByteStream); 
    byte [] outArray = outByteStream.toByteArray(); 
    response.setContentType("application/ms-excel"); 
    response.setContentLength(outArray.length); 
    response.setHeader("Expires:", "0"); // eliminates browser caching 
    if(pageDef == "promo" || pageDef.equals("promo")) 
     response.setHeader("Content-Disposition", "attachment; filename=PROMO-" + sd.format(dt) + ".xls"); 
    else if(pageDef == "incomplete" || pageDef.equals("incomplete")) 
     response.setHeader("Content-Disposition", "attachment; filename=INCOM-" + sd.format(dt) + ".xls"); 
    else 
     response.setHeader("Content-Disposition", "attachment; filename=ST-" + sd.format(dt) + ".xls"); 
    OutputStream outStream = response.getOutputStream(); 
    outStream.write(outArray); 
    outStream.flush(); 
    outStream.close(); 

編輯:方法write() - >寫出此工作簿的OutputStream。

檢查API:http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html#write%28java.io.OutputStream%29

所以,這已經派出輸出/響應,然後你試圖設置響應,並從響應得到OutputStream

有沒有問題的任何引用或代碼相關的第二錯誤javax.servlet.ServletException: File &quot;/common/err/errorPage.jsp&quot; not found

這可能是因爲你試圖轉發或重定向到errorPage.jsp從你的servlet不給定路徑存在。

+0

我已經包含了wb。它是「HSSFWorkbook wb = new HSSFWorkbook();」我必須在wb.write之前執行什麼?請解釋我。我仍然是Java新手。 – Raymond 2013-04-04 10:51:06

+0

哦,我的壞..請參閱編輯 – 2013-04-04 11:37:48

+0

我做你的忠告..錯誤消失,但當我打開我的Excel,沒有什麼..!請幫忙! – Raymond 2013-04-05 04:15:27

0

這是我的JSP文件中的代碼

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>Insert title here</title> 
</head> 
<body><%@ page import="java.io.*" %> 
<%@ page import="org.apache.poi.ss.usermodel.Workbook"%> 
<%@ page import="org.apache.poi.ss.usermodel.Cell"%> 
<%@ page import="org.apache.poi.hssf.usermodel.HSSFCell"%> 
<%@ page import="org.apache.poi.hssf.usermodel.HSSFRow"%> 
<%@ page import="org.apache.poi.ss.usermodel.Row"%> 
<%@ page import="org.apache.poi.ss.usermodel.Sheet"%> 
<%@ page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%> 
<%@ page import="org.apache.poi.hssf.usermodel.HSSFSheet"%> 
<%@ page import="java.sql.*"%> 

<%!int i=1; %> 
<%!String Id; %> 
<% Id=(String)request.getAttribute("id"); %> 
<%HSSFWorkbook wb = new HSSFWorkbook(); 
HSSFSheet sheet = wb.createSheet(); 
    try { 
    java.sql.Connection con; 
    Class.forName("com.mysql.jdbc.Driver"); 
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/custinfo","root","abc"); 
     Statement st= con.createStatement(); 
     out.println("hello world"); 
    ResultSet rs=st.executeQuery("select name ,state ,balance,description from customerdata where customerid='"+Id+"'"); 

    HSSFRow row = sheet.createRow((short)0); 
    row.createCell((short)0).setCellValue("NAME"); 
    row.createCell((short)1).setCellValue("STATE"); 
    row.createCell((short)2).setCellValue("BALANCE"); 
    row.createCell((short)3).setCellValue("DESCRIPTION"); 
    while(rs.next()) 
    { 
     out.println("hello world data");  
     HSSFRow row1 = sheet.createRow((short)i); 
     row1.createCell((short)0).setCellValue(rs.getString("name")); 
     row1.createCell((short)1).setCellValue(rs.getString("state")); 
    row1.createCell((short)2).setCellValue(rs.getString(3)); 
    row1.createCell((short)3).setCellValue(rs.getString(4)); 
    i=i+1; 
    sheet.autoSizeColumn((short)1); 

    } 

    } 
    catch(SQLException e) { 
    out.println("SQLException caught: " +e.getMessage()); 
    }%> 
// create a small spreadsheet 
<% 

%> 
<% 

ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); 
wb.write(outByteStream); 
byte [] outArray = outByteStream.toByteArray(); 
response.setContentType("application/ms-excel"); 
response.setContentLength(outArray.length); 
response.setHeader("Expires:", "0"); // eliminates browser caching 
response.setHeader("Content-Disposition", "attachment; filename=testxls.xls"); 
OutputStream outStream = response.getOutputStream(); 
outStream.write(outArray); 
outStream.flush(); 

%> 
</body> 
</html> 

而在我的Action類的我已經給這個

<action name="DownloadExcel" class="bank.ReportGenerator" method="downloadExcel"> 
      <result name="success">/download.jsp</result> 

     </action> 

,並在類ReportGenerator我給

package bank; 
import com.opensymphony.xwork2.ActionSupport; 
import java.sql.*; 
import java.util.Collection; 
import java.util.Iterator; 
import java.util.*; 

public class ReportGenerator extends ActionSupport { 


    private String id; 

    public String getId() { 
     return id; 
    } 
    public void setId(String id) { 
     this.id = id; 
    } 
    public String pieChart() throws Exception 
    { 
     return SUCCESS; 


    } 
    public String downloadExcel() throws Exception 
    { 
     return SUCCESS; 


    } 

} 

你可以改變代碼中的查詢和數據庫使它爲你工作。只有JSP文件足以生成一個excel文件內容。

相關問題