将数据导出Excel格式

最近做的一个项目涉及到导出功能,第一次写做下笔记,此方法用的是poi插件:

1.下载poi-3.6-20091214.jar加载到工程中

2.如果在后台写代码,一个小例子,代码如下:

package com.test;
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("中文字符");
    
  try   { 
         output.flush(); 
         wb.write(output); 
         output.close();
 }   catch   (IOException   e)   { 
         e.printStackTrace(); 
         System.out.println( "Output   is   closed "); 
 } 
 }
}

3.由于要让数据有提示的打开或者保存,我们可以加一个jsp页面,然后访问这个页面直接弹出Excel打开框:
jsp页面:

<%@ page contentType="application/vnd.ms-excel" language="java" import="java.io.OutputStream,java.util.*,com.test.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());
OutputStream ot=response.getOutputStream();
out.clear();
out = pageContext.pushBody();
%>

一定要注意jsp代码里的最后三行:

OutputStream ot=response.getOutputStream();//这一步是要导入java.io.OutputStream
out.clear();
out = pageContext.pushBody();

丢了这三行在运行程序的时候后台会报错:

“严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response”

还有就是无论代码是在jsp页面写还是在后台写,这样在jsp页面里加上上面的三行代码就不会在后台报错了。

原文地址:https://www.cnblogs.com/zhangkaijia/p/3024665.html