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)有用。
標(biāo)簽:烏蘭察布 吉林 開封 臨汾 山南 白銀 自貢 銅川
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《jsp利用POI生成Excel并在頁面中導(dǎo)出的示例》,本文關(guān)鍵詞 jsp,利用,POI,生成,Excel,并在,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。