java中導出Excel有兩個組件可以使用,一個是jxl,一個是POI,我這里用的是POI。導出是可以在服務器上生成文件,然后下載,也可以利用輸出流直接在網頁 中彈出對話框提示用戶保存或下載。生成文件的方式會導致服務器中存在著垃圾文件,實現方式不太優雅,所以這里我采用的是后面直接通過輸出流的方式。
1、修改WEB服務器的CONF/web.xml,添加 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文件下載或保存了,這在一些信息系統中相當有用。
您可能感興趣的文章:- POI通過模板導出EXCEL文件的實例
- 基于apache poi根據模板導出excel的實現方法
- Springboot使用POI實現導出Excel文件示例
- 詳解poi+springmvc+springjdbc導入導出excel實例
- Java利用POI實現導入導出Excel表格示例代碼
- asp.net使用npoi讀取excel模板并導出下載詳解
- java使用poi導出Excel的方法
- POI導出Excel報錯No such file or directory的解決方法
- Java poi導出Excel下載到客戶端
- POI通用導出Excel(.xls,.xlsx)的方法