日期:2014-05-16 浏览次数:20387 次
在servlet、javaBean、。。。中生成一个HSSFWorkbook,再让它返回给JSP页面。
在JSP页面中:首先设置页面响应的MIME类型,
即:response.setContentType("application/msexcel")
再设置响应标题:
response.setHeader("Content-disposition","inline; filename=data.xls") //attachment
这里有两种形式:inline/attachment
在JSP页面中得到workbook后--》new 一个输出流:
OutputStream os = response.getOutputStream()
再把workbook写入输出流中——》
就可以保存或打开以Excel文件形式的文件。
最初的一个代码如下:
java类:
package com.hhxy.doexcel; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public class DownExcel { public HSSFWorkbook downExcel (){ HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell((short)0); cell.setCellValue("The first cell!"); cell = row.createCell((short)1); cell.setCellValue("Second"); cell = row.createCell((short)2); cell.setCellValue("Third"); cell = row.createCell((short)3); cell.setCellValue("Fouth"); return wb; } } JSP布面如下: <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@ page import = "com.hhxy.doexcel.*" %> <%@ page import = "java.util.*" %> <%@ page import = "java.io.*"%> <%@ page import = "org.apache.poi.hssf.usermodel.HSSFWorkbook" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Excel档案呈现方式</title> </head> <body> <% String excel = request.getParameter("excel"); if(excel !=null && "true".equals(excel)){ response.setContentType("application/msexcel"); response.setHeader("Content-disposition","inline; filename=data.xls"); //attachment DownExcel test = new DownExcel(); HSSFWorkbook wb = test.downExcel(); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); }else{ %> <div align="center"><a href="TestExcel.jsp?excel=true">生成Excel</a></div> <%}%> </body>
?