论坛首页 Java企业应用论坛

生成Excel并在客户端下载的JSF实现

浏览 17943 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-05-29  
国内项目中,应用excel作为数据文件导出的功能,很常见,也很能为客户解决问题,方便客户制作数据报表,从效率和性能上讲,有2种实现方式:一,返回数据结果集到页面,直接展现为excel,只能应用于很少量的数据,否则客户肯定不能接受;二,在服务端得到数据结果集,调用各种工具类,将数据写入文件,如写入dbf和excel文件,然后提供客户端下载,这种方式应该是首选方案,如楼主的解决方案,将系统运行的压力交给服务器,在服务器上开辟一个专门的空间来存放文件,反之在客户端,还能利用各种下载工具进行文件下载,具备很好的性能和可扩展性
0 请登录后投票
   发表时间:2008-06-11  
老大们,我用的就是楼主提供的源码,为什么老出错呢??

生成报表有误:java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.Object;
0 请登录后投票
   发表时间:2008-06-11  
修改了一下源码,问题解决了:
http://purebit.net/showtopic.aspx?page=end&topicid=9744#11013

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
* 本工具类解决了java到处Excel,并同时实现了客户端下载 不足之处:下载方法传入的文件名不支持中文
*
* @author Java程序员,专注于Java领域的开发和新技术的研究
*
*/
public class ExcelUtils {

    private static String sheetName = "data";
    private HSSFWorkbook wb;
    private HSSFSheet sheet;
    private HSSFRow row;
    private HSSFCell cell;
    private HSSFFont font;
    private HSSFCellStyle cellStyle;
    private FileOutputStream fileOut;

    public ExcelUtils() {
        wb = new HSSFWorkbook();
    }

    /**
     * @param excelName
     *            excel名称。
     * @param list
     *            这个list里面存放的是对象数组。数组元素可以转化为字符串显示的。这个对象数组一般对应数据库里的几列。
     * @param firstRowValue
     */
    public void outputExcel(String excelName, List list, String[] firstRowValue) {
        try {
            this.createSheet(firstRowValue);
            this.setValueToRow(excelName, list);
        } catch (Exception ex) {
            System.out.print(ex);
        }
        // System.out.println("文件名是:" + excelName);
        downloadFile(excelName);
    }

    public void outputExcel(String excelName, List list) {
        try {
            this.setValueToRow(excelName, list);
        } catch (Exception e) {
        // TODO: handle exception
        }
        downloadFile(excelName);
    }

    private void setValueToRow(String excelName, List list) {
        // 获得JSF上下文环境
        FacesContext context = FacesContext.getCurrentInstance();
        // 获得ServletContext对象
        ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
        // 取得文件的绝对路径
        excelName = servletContext.getRealPath("/UploadFile") + "/" + excelName;
        System.out.println("生成文件的路径是:" + excelName);
        ArrayList obj;
        try {
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                obj = (ArrayList)list.get(i);
                this.createCell(row, obj);
            }
            fileOut = new FileOutputStream(excelName);
            wb.write(fileOut);

        } catch (Exception ex) {
            System.out.print("生成报表有误:" + ex);
        } finally {
            try {
                fileOut.flush();
                fileOut.close();
            } catch (Exception e) {
                System.out.println("ExcelUtil.setValueToRow()");
            }
        }
    }

    private void createSheet(String[] firstRowValue) {
        try {
            sheet = wb.createSheet(ExcelUtils.sheetName);
            row = sheet.createRow(0);
            font = wb.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            cellStyle = wb.createCellStyle();
            cellStyle.setFont(font);
            for (int i = 0; i < firstRowValue.length; i++) {
                cell = row.createCell((short) i);
                cell.setCellStyle(cellStyle);
                cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                cell.setCellValue(firstRowValue[i]);
            }
        } catch (Exception ex) {
            System.out.print(ex);
        }
    }

    private void createCell(HSSFRow row, ArrayList obj) {
        try {
            for (int i = 0; i < obj.size(); i++) {
                cell = row.createCell((short) i);
                cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                cell.setCellValue(obj.get(i).toString());
            }
        } catch (Exception ex) {
            System.out.print(ex);
        }
    }

    /**
     * <p>
     * 功能说明:根据提供的文件名下载文件,不支持中文文件名
     * </p>
     * 此方法由yongtree添加,实现文件生成后的下载
     *
     * @param strfileName
     *            String
     * @return void
     */
    private static void downloadFile(String strfileName) {
        try {
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/UploadFile") + "/" + strfileName;
            File exportFile = new File(excelName);
            HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition",
                    "attachment; filename=" + strfileName);
            httpServletResponse.setContentLength((int) exportFile.length());
            httpServletResponse.setContentType("application/x-download");
            // httpServletResponse.setContentType("application/vnd.ms-excel");

            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        FacesContext.getCurrentInstance().responseComplete();
    }
}
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics