欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jsp利用POI生成Excel并在頁面中導(dǎo)出的示例

 更新時(shí)間:2016年10月24日 15:24:52   作者:shangyu79  
本篇文章主要是介紹jsp利用POI生成Excel并在頁面中導(dǎo)出的示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。

java中導(dǎo)出Excel有兩個(gè)組件可以使用,一個(gè)是jxl,一個(gè)是POI,我這里用的是POI。導(dǎo)出是可以在服務(wù)器上生成文件,然后下載,也可以利用輸出流直接在網(wǎng)頁 中彈出對(duì)話框提示用戶保存或下載。生成文件的方式會(huì)導(dǎo)致服務(wù)器中存在著垃圾文件,實(shí)現(xiàn)方式不太優(yōu)雅,所以這里我采用的是后面直接通過輸出流的方式。

1、修改WEB服務(wù)器的CONF/web.xml,添加 Xml代碼

<mime-mapping> 
    <extension>xls</extension> 
    <mime-type>application/vnd.ms-excel</mime-type> 
 </mime-mapping> 

如果不添加這個(gè),那么在網(wǎng)頁中下載的時(shí)候就變成了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代碼,并且除了<% %> 中間的代碼,其它的地方不要有空格。否則在導(dǎo)出文件的時(shí)候會(huì)在后臺(tái)出現(xiàn)異常,雖然不影響程序的使用,到時(shí)令人看起來 不太舒服

3、WriteExcel.java  生成Excel的JavaBean,復(fù)雜的應(yīng)用請(qǐng)查看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 ");  
 }  
 } 
} 

通過以上三步,應(yīng)該可以直接生成Excel文件下載或保存了,這在一些信息系統(tǒng)中相當(dāng)有用。

相關(guān)文章

最新評(píng)論