最近项目要用poi+webflow实现到处excel的功能,直接导出到服务器端以实现,先不想在服务器端保存临时文件,就是当用户点击导出按钮时弹出一个弹出保存框,类似于”目标另存为“
export_flow.xml文件如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE flow PUBLIC "-//SPRING//DTD WEBFLOW 1.0//EN"
"http://www.springframework.org/dtd/spring-webflow-1.0.dtd">
public class ExportModelExcel {
HSSFWorkbook wb = new HSSFWorkbook();
public FileOutputStream ExportModel(ModelInfo modelInfo) throws Exception {
System.out.println
int sheetNumber = 0;
HSSFSheet sheet;
while (sheetNumber < SHEET_HANDLERS.length && modelInfo != null) {
ISheetHandler sheetHandler = SHEET_HANDLERS[sheetNumber];
try {
sheet = wb.createSheet(SHEETS[sheetNumber]);
sheetHandler.process(sheet, modelInfo, this.getCellHeadStyle(),
this.getCellDataStyle());
} catch (SheetHandlerException e) {
throw new ModellerException( ModellerExceptionEnums.EXCEL_MODELLER_EXCEPTION, e);
}
sheetNumber++;
}
FileOutputStream fileOut = new FileOutputStream("test.xls");
wb.write(fileOut);
fileOut.close();
return fileOut;
}
}
exportexcel.jsp:
<%@ page contentType="application/vnd.ms-excel" %>
<%response.addHeader("Content-Disposition", "attachment;filename=test.xls");%>
${requestScope.fileOut};
现在导出的excel文件打开报excel的格式与文件扩展名指定的格式不一致,打开前请验证文件,点是后,excel中显示 java.io.FileOutputStream@1c0c8b3
用过的兄弟多多指点,先谢了!
晕,程序写错了,大错特错。
错误1:
${requestScope.fileOut};
这样写最多把这个对象的toString()输出到浏览器。
错误2:
ExportModel()这个方法错了
这里你的实现只是把内容写入了test.xls中,而这个文件是本地的文件。而返回的fileoutputstream已经被使用过了,对后面毫无用处。
正确的方法应该把excel内容写入浏览器应答对象的输出流中(response.getOutputStream()):
1,获取HSSFWorkbook 对象wb(已经实例化数据)
2,jsp中调用wb.write(request.getOutputStream())
[code="java"]
<%@ page contentType="application/vnd.ms-excel" %>
<%response.addHeader("Content-Disposition", "attachment;filename=test.xls");%>
${wb.write(response.getOutputStream())};
[/code]
大致思路就是这样
另外注意jsp会把本身代码中换行符号等输出到 输出流中,这个对于文件下载类程序来说会导致数据不正确,把所有<%%>和<%%>中间的换行符号去掉吧