解决getOutputStream() has already been called for this response

116 篇文章 0 订阅
java.lang.IllegalStateException: getOutputStream() has already been called for this response

//strut2 导出excel


//解决问题的代码

HSSFWorkbook workbook=productEcel(list,partTimer);
response.reset();
response.setContentType("contentType=application/vnd.ms-excel");
response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode("统计.xls","utf-8"));
workbook.write(response.getOutputStream());
response.flushBuffer();



//出现异常的原因

产生这样的异常原因:是web容器生成的servlet代码中有out.write(""),这个和JSP中调用的response.getOutputStream()产生冲突.即Servlet规范说明,不能既调用response.getOutputStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出IllegalStateException,因为在jsp中,out变量实际上是通过response.getWriter得到的,你的程序中既用了response.getOutputStream,又用了out变量,故出现以上错误。



//导出 excel

public String exportRedactor(){
HttpServletRequest request =this.getRequest();
HttpServletResponse response=null;
FbbServiceClient service=null;
ManagerUser user= (ManagerUser)request.getSession(true).getAttribute(Constants.SESSION_USER);
InputStream is = null;
PrintWriter out=null;
try {
method="";
response=this.getResponse();
response.setCharacterEncoding("utf-8");

service=new FbbServiceClient();
FbbService.Client client=service.open();
if(partTimer == null)
partTimer = new PartTimer();
partTimer.setSourceId(2);
List<PartTimer> list = client.getStatisticsPartTimer(user.getId(), user.getSignature(), partTimer);
String result="";

if(list==null || list.size()<=0){
request.setAttribute("msg","没有数据需要导出");
return SUCCESS;
}else{HSSFWorkbook workbook=productEcel(list,partTimer);
response.reset();
response.setContentType("contentType=application/vnd.ms-excel");
response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode("统计.xls","utf-8"));
workbook.write(response.getOutputStream());
response.flushBuffer();
}

} catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg","导出数据出现异常");
logger.error("errorcode ::: " + e.getMessage(), e);
}finally{
if(service!=null)
service.close();
if(out!=null){
try {
out.close();
} catch (Exception e) {
logger.error("errorcode ::: " + e.getMessage(), e);
}
}

if(is!=null){
try {
is.close();
} catch (Exception e) {
logger.error("errorcode ::: " + e.getMessage(), e);
}
}
}
return NONE;


private HSSFWorkbook productEcel(List<PartTimer> list,PartTimer partTimer) throws Exception {

// 创建工作表和标题
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook();
} catch (Exception e) {
e.printStackTrace();
}

// 定义字体
HSSFFont celltbnamefont = workbook.createFont();
celltbnamefont.setFontHeightInPoints((short) 12); // 字体大小
celltbnamefont.setColor((short) (HSSFFont.COLOR_NORMAL)); // 颜色
celltbnamefont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 粗体




// 定义 date 的数据样式
HSSFCellStyle datestyle = workbook.createCellStyle();
HSSFDataFormat df = workbook.createDataFormat();
datestyle.setAlignment((short) HSSFCellStyle.ALIGN_LEFT);
datestyle.setDataFormat(df.getFormat("yyyy-mm-dd hh:mm:ss"));

// 定义 int 的数据样式
HSSFCellStyle intdatestyle = workbook.createCellStyle();
intdatestyle.setAlignment((short) HSSFCellStyle.ALIGN_LEFT);

// 定义 float 的数据样式
HSSFCellStyle floatdatestyle = workbook.createCellStyle();
floatdatestyle.setAlignment((short) HSSFCellStyle.ALIGN_LEFT);
df = workbook.createDataFormat();
floatdatestyle.setDataFormat(df.getFormat("#.##"));

// 定义 long 的数据样式
HSSFCellStyle longdatestyle = workbook.createCellStyle();
longdatestyle.setAlignment((short) HSSFCellStyle.ALIGN_LEFT);

//title样式
HSSFCellStyle titledatestyle = workbook.createCellStyle();
titledatestyle.setAlignment((short) HSSFCellStyle.ALIGN_CENTER_SELECTION);
titledatestyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
//titledatestyle.setFillBackgroundColor(HSSFColor.BLUE.index2);
titledatestyle.setFont(celltbnamefont);

// 定义列的样式
HSSFCellStyle items_style = workbook.createCellStyle();
items_style.setAlignment((short) HSSFCellStyle.ALIGN_CENTER); // 设置对其方式
items_style.setFont(celltbnamefont);
items_style.setWrapText(false); // 设置自动换行
items_style.setFillForegroundColor(HSSFColor.ROSE.index);// 设置背景色
items_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
items_style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
items_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
items_style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
items_style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

HSSFCellStyle row_style = workbook.createCellStyle();
titledatestyle.setAlignment((short) HSSFCellStyle.ALIGN_CENTER_SELECTION);
titledatestyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

/*
row_style.setAlignment((short) HSSFCellStyle.ALIGN_CENTER); // 设置对其方式
row_style.setFont(celltbnamefont);
row_style.setWrapText(false); // 设置自动换行
row_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
row_style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
row_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
row_style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
row_style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
*/


int rowIndex = 0;
String sheetName="兼职信息及酬劳统计";
String head="兼职信息及酬劳统计";
if(!Misc.isStringEmpty(partTimer.getStime())){
head+="(时间:"+partTimer.getStime()+"-"+partTimer.getEtime()+")";
}

HSSFSheet sheet = workbook.createSheet(sheetName); // 创建工作区
//sheet.setDefaultRowHeightInPoints(100);
//sheet.setDefaultRowHeight((short)100);


//合并14列 用于写 表格名称
Region region = new Region();
region.setRowFrom(0);
region.setRowFrom(0);
region.setColumnFrom((short)0);
region.setColumnTo((short)14);
sheet.addMergedRegion(region);

//将list 数据 打印到表格中
HSSFCell cell;

//表头信息
HSSFRow heandRow = sheet.createRow((short) rowIndex);
cell=heandRow.createCell(0);
cell.setCellStyle(titledatestyle);
cell.setCellValue(head);
heandRow.setHeightInPoints(30);



// 创建数据列名
String titles[] = {"序号","姓名","xx名","xxID","性别","QQ","手机", "微信","微博名及粉丝","应发数量","实发数量","审核通过数","酬劳","支付宝","备注"};

HSSFRow row =sheet.createRow((short) (++rowIndex));
// 加入 标题
for (int i = 0; i < titles.length; i++) {
cell = row.createCell(i, Cell.CELL_TYPE_STRING); // 设置 列类型
if (i ==8 || i ==11 || i==14) {
sheet.setColumnWidth(i, 5500);
} else {
sheet.setColumnWidth(i, 4000);
}
cell.setCellValue(titles[i]);
cell.setCellStyle(items_style);
}
Iterator<PartTimer> it = list.iterator();
int index=0;
while (it.hasNext()) {
HSSFRow dataRow = sheet.createRow((short) (++rowIndex));
dataRow.setHeightInPoints(20);
dataRow.setRowStyle(row_style);

PartTimer obj = it.next();
cell = dataRow.createCell(0, Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(longdatestyle);
cell.setCellValue(++index);

cell = dataRow.createCell(1, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getRealName());

cell = dataRow.createCell(2, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getUserName());

cell = dataRow.createCell(3, Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(longdatestyle);
cell.setCellValue(obj.getId());

cell = dataRow.createCell(4, Cell.CELL_TYPE_STRING);
cell.setCellValue( "1".equals(obj.getPgender()) ? "男":"女");

cell = dataRow.createCell(5, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getPqq());

cell = dataRow.createCell(6, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getPmobile());

cell = dataRow.createCell(7, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getPweixin());

cell = dataRow.createCell(8, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getPweibo());

cell = dataRow.createCell(9, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getRequire());

cell = dataRow.createCell(10, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getPicCount());

cell = dataRow.createCell(11, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getPassCount());


cell = dataRow.createCell(12, Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(floatdatestyle);
cell.setCellValue(obj.getRepay());

cell = dataRow.createCell(13, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getAlipay());

cell = dataRow.createCell(14, Cell.CELL_TYPE_STRING);
cell.setCellValue(obj.getRemark());

}
//sheet.setColumnWidth(9, 2730);
//sheet.setColumnWidth(12, 2730);



/*HSSFRow dataRow = sheet.createRow((short) (++rowIndex));
cell = dataRow.createCell(0, Cell.CELL_TYPE_STRING);
cell.setCellStyle(intdatestyle);
cell.setCellValue("合计:");

cell = dataRow.createCell(1, Cell.CELL_TYPE_STRING);
cell.setCellValue("");

// 添加 公式
cell = dataRow.createCell(2, Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(longdatestyle);
cell.setCellFormula("SUM(" + getColLetter(2)
+ sheet.getRow(2).getCell(2).getRowIndex() + ":"
+ getColLetter(2)
+ sheet.getRow(sheet.getLastRowNum()).getCell(2).getRowIndex()
+ ")");
// 添加 公式
cell = dataRow.createCell(3, Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(longdatestyle);
cell.setCellFormula("SUM(" + getColLetter(3)
+ sheet.getRow(2).getCell(3).getRowIndex() + ":"
+ getColLetter(3)
+ sheet.getRow(sheet.getLastRowNum()).getCell(3).getRowIndex()
+ ")");*/

/*String workDir = ServletActionContext.getServletContext().getRealPath("/");

String workddd = workDir.replaceAll("\\\\", "/");

Calendar calendar = Calendar.getInstance();
String month = calendar.get(Calendar.YEAR) + "/"
+ (calendar.get(Calendar.MONTH) + 1);
String filePath = "newsxls/adxls/" + month + "/";
File f = new File(workDir + filePath);
if (!f.isDirectory()) {
f.mkdirs();
}

String fileNameCode = java.util.UUID.randomUUID().toString();
String completeFilePath = workddd + filePath + fileNameCode + ".xls";
FileOutputStream fileOut = new FileOutputStream(completeFilePath);
workbook.write(fileOut);
fileOut.flush();
fileOut.close();*/

return workbook;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值