1

我无法弄清楚是什么问题。我试过了,但错误仍然存​​在。

我的程序是导出到 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 但仍然出现错误。

英语不是我的母语。对不起,如果我输入错误。

提前致谢。

4

3 回答 3

1

我猜你的错误与这段代码有关(不是 apache poi api):

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

因为您正在刷新和关闭 servlet 中的输出流,所以在响应返回到客户端之前尝试写入输出流的任何内容都将导致抛出 IllegalStateException。通常最好将 flush() 和 close() 留给 servletcontainer,除非你真的知道你在做什么。
尝试删除 flush() 和 close(),并检查您拥有的其他 servlet 是否正在做同样的事情。

于 2013-04-04T03:15:34.393 回答
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()-> 将此工作簿写入输出流。

检查 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 转发或重定向。

于 2013-04-04T06:42:29.183 回答
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 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 文件。

于 2013-06-01T07:02:43.603 回答