jsp利用POI直接生成Excel并在页面中导出
java中导出Excel有两个组件可以使用,一个是jxl,一个是POI,我这里用的是POI。导出是可以在服务器上生成文件,然后下载,也可以利用输出流直接在网页
中弹出对话框提示用户保存或下载。生成文件的方式会导致服务器中存在着垃圾文件,实现方式不太优雅,所以这里我采用的是后面直接通过输出流的方式。
1、修改WEB服务器的CONF/web.xml,添加
<mime-mapping> <extension>xls</extension> <mime-type>application/vnd.ms-excel</mime-type> </mime-mapping>
<%@ page contentType="application/vnd.ms-excel" language="java" import="java.util.*,com.shangyu.action.WriteExcel" pageEncoding="GBK"%><%response.setHeader("Content-Disposition","attachment;filename=test123.xls");//指定下载的文件名response.setContentType("application/vnd.ms-excel"); WriteExcel we=new WriteExcel();we.getExcel("111.xls",response.getOutputStream());%>package com.shangyu.action;import java.io.*;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFCell;public class WriteExcel { public void getExcel(String sheetName,OutputStream output) { HSSFWorkbook wb=new HSSFWorkbook(); HSSFSheet sheet1=wb.createSheet("sheet1"); HSSFRow row=sheet1.createRow((short)0); HSSFCell cell=row.createCell((short)0); cell.setCellValue(1); row.createCell((short)1).setCellValue(2); row.createCell((short)2).setCellValue(3); row.createCell((short)3).setCellValue("中文字符"); row=sheet1.createRow((short)1); cell=row.createCell((short)0); cell.setCellValue(1); row.createCell((short)1).setCellValue(2); row.createCell((short)2).setCellValue(3); row.createCell((short)3).setCellValue("中文字符"); //FileOutputStream fileout=new FileOutputStream("workbook.xls"); try { output.flush(); wb.write(output); output.close(); } catch (IOException e) { e.printStackTrace(); System.out.println( "Output is closed "); } }}通过以上三步,应该可以直接生成Excel文件下载或保存了,这在一些信息系统中相当有用。