我也用的是POI生成Excel文件,
由于表格比较复杂,我采用了Excel模板,因此只要把数据填到表格内再适当修改某些单格样式就可以了, 但由于表格太复杂, 每次超过1000条记录就会内存溢出.我觉得如果表格不是很复杂,可以生成CSV文件,这样速度快很多,也不会出现内存溢出的情况.

解决方案 »

  1.   

    import javax.servlet.ServletRequest;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.servlet.jsp.JspWriter;import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.actions.DispatchAction;
    import org.apache.log4j.*;
    import java.sql.*;
    import java.util.HashMap;import org.hibernate.*;import org.apache.poi.hssf.record.FontRecord;
    import org.apache.poi.hssf.usermodel.*;
    import java.io.*;import com.scitel.common.hibernate.*;/**
       Author peiDW  保留署名权
       email : pdw2009 At yahoo.com.cn
       blog  : http://pdw2009.54bk.com
    */
    public class ReportAction extends DispatchAction{
    Logger logger=Logger.getLogger(ReportAction.class);
    public void excelReport(ActionMapping actionMapping,
    ActionForm actionForm, HttpServletRequest httpServletRequest,
    HttpServletResponse httpServletResponse) {

    httpServletResponse.setContentType("application/vnd.ms-excel");
    ServletRequest request=(ServletRequest)httpServletRequest;
    String str_sql=request.getParameter("str_query");
    String str_title=request.getParameter("str_title");
    String str_head=request.getParameter("strGridTitle");
    HttpSession session=httpServletRequest.getSession();
    HashMap hm=(HashMap)session.getAttribute("gzmas_popedom");
    try {
    OutputStream os=httpServletResponse.getOutputStream();
    if(hm==null||!hm.containsKey("Report_Manager")) {
    String a="你没有权限,所以不能获取数据!";
    byte bytes[]=new byte[a.length()];
    bytes=a.getBytes();
    os.write(bytes);
    }else {
    os.write(getWorkbook(str_sql,str_title,str_head).getBytes());
    }
    os.flush();
    os.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    //return null;
    }

    public void  csvReport(ActionMapping actionMapping,
    ActionForm actionForm, HttpServletRequest httpServletRequest,
    HttpServletResponse httpServletResponse) {
    httpServletResponse.setContentType("application/vnd.ms-excel;charset=gb2312");
    ServletRequest request=(ServletRequest)httpServletRequest;
    String str_sql= (String) request.getParameter("strquery");
    String str_title=request.getParameter("strtitle");
    String str_head=request.getParameter("strGridTitle");
    HttpSession session=httpServletRequest.getSession();
    HashMap hm=(HashMap)session.getAttribute("gzmas_popedom");
    try {
    PrintWriter out=httpServletResponse.getWriter();
    if(hm==null||!hm.containsKey("Report_Manager")) {
    out.println("你没有权限,所以不能获取数据!");
    }else {
    out.println(getCsv(str_sql,str_title,str_head));
    }
    out.flush();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
        /**
         * 以CSV方的方式生成Excel表格
         * @param str_sql
         * @param title
         * @return
         */
    public String getCsv(String str_sql,String title,String str_head) {
    StringBuffer sb=new StringBuffer();
    Connection conn=null;
    Session session=null;
    Statement stmt=null;
    ResultSet rec=null;
    try {
    session=CommonUtils.currentSession();
    conn=session.connection();
    stmt=conn.createStatement();
    rec=stmt.executeQuery(str_sql);
    ResultSetMetaData rmd=rec.getMetaData();
    sb.append("     "+title+"    ").append("\n");
    String[] ary = str_head.split(",");
    for(int k=0;k<ary.length;k++) {
    sb.append(ary[k]).append((char)9);
    }
    while(rec.next()) {
    sb.append("\n");
    for(int i=1;i<=rmd.getColumnCount();i++) {
    String temp=rec.getString(i);
    if(temp==null) {
    temp="";
    }
    String str_value=temp.replaceAll("[\\\n\\\t]"," ");
    sb.append(str_value).append((char)9);
    }
    }
    }catch(Exception e) {
    sb.append("生成数据出错!");
    e.printStackTrace();
    }finally {
    try {
    if(rec!=null) {
    rec.close();
    }
    if(stmt!=null) {
    stmt.close();
    }
    CommonUtils.closeSession();
    }catch(Exception e) {
    //logg.er.error(e);
    e.printStackTrace();
    }
    }

    return sb.toString();
    }
       /**
        * 使用POI生成Excel
        * @param str_sql
        * @param title
        * @return
        */
    public  HSSFWorkbook getWorkbook(String str_sql,String title,String str_head) {
    HSSFWorkbook result=new HSSFWorkbook();
    Connection conn=null;
    Session session=null; 
    Statement stmt=null;
    ResultSet rec=null;
    try {
    session=CommonUtils.currentSession();
    conn=session.connection();
    stmt=conn.createStatement();
    rec=stmt.executeQuery(str_sql);
    HSSFSheet sheet=result.createSheet("sheet1");
    ResultSetMetaData rmd=rec.getMetaData();
    //excel标题 HSSFRow row0=sheet.createRow(0);
    HSSFCell cell0=row0.createCell((short)2);
    cell0.setEncoding(HSSFCell.ENCODING_UTF_16);
    cell0.setCellValue(title);

    HSSFRow row1=sheet.createRow(1);
    String ary[]=str_head.split(",");
        for(int k=0;k<ary.length;k++) {
         HSSFCell cell=row1.createCell((short)k);
         cell.setEncoding(HSSFCell.ENCODING_UTF_16);
         cell.setCellValue(ary[k]);
        }
    int i=2;
    while(rec.next()) {
    HSSFRow row=sheet.createRow(i);
    for(int k=1;k<=rmd.getColumnCount();k++) {
    HSSFCell cell=row.createCell((short)(k-1));
    cell.setEncoding(HSSFCell.ENCODING_UTF_16);
    cell.setCellValue(rec.getString(k));
    }
    i++;
    }
    System.out.println(result.getBytes().length);
    return result;
    }catch(Exception e) {
    //logger.error(e);
    e.printStackTrace();
    }finally {
    try {
    if(rec!=null) {
    rec.close();
    }
    if(stmt!=null) {
    stmt.close();
    }
    CommonUtils.closeSession();
    }catch(Exception e) {
    //logger.error(e);
    e.printStackTrace();
    }
    }
    return null;
    }

    public static void main(String args[]) {
    String aa="afsadfasf"+"\n"+"dfasdf";
    char c=(char)9;
    String vv=aa+c+"sgfdgdfsgdsfg";
    String result=vv.replaceAll("[\\\n\\\t]","-");
    System.out.println("result->"+result);
    }}===========================================
    如果你数据量大的话请用CSV方式生成Excel,这是我前几天写的。现贴出来,只想赚你那100分专家分
      

  2.   

    to:pdw2009(捡垃圾去上网)100分没问题,关键在于csv不能生成格式,我需要有格式的excel,
    其实只需要 对齐方式,边框黑色,单元格合并,这3种不知道csv格式可不可以实现
      

  3.   

    excel还是有问题,最多只能插入65536条数据,害得我每次都要分成几个excel分别统计。实在不行你也像我一样分块统计吧!
    我用的是jxl
      

  4.   

    我当初也是用张嘎说的方法,尽量的大。
    另外一个JExcel API 好象比POI强些。
      

  5.   

    应该是cellStyle的问题,由于数据量大,cellStyle会消耗很多资源.建议根据每列生成一个cellstyle对象. 其他地方能用excel模板的就尽量用excel模板.
      

  6.   

    poi就是这样,数据量一大就死,还有一种办法导出excel并且带有格式,就是把数据显示在网页上,写客户端javascript转成excel,csdn的javascript版里有讨论,楼主自己去找找吧。
      

  7.   

    客户端的javascript在数据量大的时候也会有问题的,常见的现象就是浏览器没有响应,其实Excel另存成的xml格式是很简单也很容易懂的,要做到你这样的简单格式一点问题都没有,而且下载的时候如果选择打开的话会自动调用excel的,不失为一种好方法,而且生成xml为文本,就没有了OOM问题。
      

  8.   

    直接在页面输出表格,设置表格样式,然后把表格输出的contentType="application/excel"看一下行不