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>
   
    如果不添加這個,那麼在網頁中下載的時候就變成了JSP文件

2、download.jsp文件

<%@ 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());
%>

注意不要有html代碼,並且除了<% %> 中間的代碼,其它的地方不要有空格。否則在導出文件的時候會在後臺出現異常,雖然不影響程序的使用,到時令人看起來
不太舒服

3、WriteExcel.java  生成Excel的JavaBean,複雜的應用請查看API

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文件下載或保存了,這在一些信息系統中相當有用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章