使用jxl导出Execl文件

这几天一直在做一个疯狂的Web项目(SSH)需求!!!

“根据客户添加的查询条件,来拼sql语句,传到Dao层的SQL语句中,查询出对应的数据。”

----页面拼写Sql语句。

而且:

自定义导出Execl的列,默认勾选全部的字段名(“id”,“姓名”,“密码”)这只是示例3个,实际项目中一共有40个字段(列),客户不想在execl中看到又臭又长的“id”,取消掉,execl就不能有“id”这一列了。

----自定义导出Execl列。

还好!已经做完,其中运用到Jxl导出Execl文件,这项小技术,在此小结一下,以备下次使用。

直接上代码,代码都有详细的注释:

UserInfo类:

class UserInfo {
    private String id;
    private String name;
    private String password;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
工具方法,网页下载方法:

  /**
     * 从服务器下载execl文件
     * 此方法属于action
     */
    public void downLoad(String filePath) throws IOException{
        File f = new File(filePath);
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        this.servletResponse.reset(); // 非常重要
        // 纯下载方式
        this.servletResponse.setContentType("application/x-msdownload");
        this.servletResponse.setHeader("Content-Disposition", "attachment; filename="
                + f.getName());
        OutputStream out = this.servletResponse.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        out.flush();
        br.close();
        out.close();
    }
创建Execl文件方法,核心:

 /**
     * 根据查询所得数据,创建对应列和行的execl
     * 此方法属于Service,
     */
    public void createMzDataExcel(FileOutputStream ouputStream) throws Exception {
        int fields=3;//列数,导出字段的数量
        //创建工作薄
        WritableWorkbook workbook = Workbook.createWorkbook(ouputStream);
        //创建新的一页
        WritableSheet sheet = workbook.createSheet("First Sheet", 0);
        //构造表头
        sheet.mergeCells(0, 0, fields, 0);//添加合并单元格,第一个参数是起始列,第二个参数是起始行,第三个参数是终止列,第四个参数是终止行
        WritableFont bold = new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//设置字体种类和黑体显示,字体为Arial,字号大小为10,采用黑体显示
        WritableCellFormat titleFormate = new WritableCellFormat(bold);//生成一个单元格样式控制对象
        titleFormate.setAlignment(jxl.format.Alignment.CENTRE);//单元格中的内容水平方向居中
        titleFormate.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//单元格的内容垂直方向居中

        //第一行标题
        Label title = new Label(0,0,"jxl导出Execl示例",titleFormate);
        sheet.setRowView(0, 600, false);//设置第一行的高度
        sheet.addCell(title);


        Label lable=null;
        //为第二行插入列名
        for(int i=0;i<fields;i++){
            int x=i+1;
            lable = new Label(i,1,"第"+x+"列",titleFormate);
            sheet.addCell(lable);
            sheet.setColumnView(i, 17);
        }

        List<UserInfo>datalist=new ArrayList<UserInfo>();
        //这里是new了一个数据来做示例,项目中是从Dao层查询得到的。
        UserInfo u1=new UserInfo();
        u1.setId("01");
        u1.setName("张三");
        u1.setPassword("111111");
        datalist.add(u1);
        
        //开始写入对应的数据
        String data;
        if(datalist.size()>0&&datalist!=null){
            UserInfo user=new UserInfo();
            for(int i=1;i<datalist.size()+1;i++){
                user=datalist.get(i-1);
                for(int m=0;m<fields;m++){
                    if(m==0){
                        data=user.getId();//第1列放字段:“id”
                    }else if(m==1){
                        data=user.getName();//第2列放字段:“name”
                    }else{
                        data=user.getPassword();//第3列放字段:“password”
                    }
                    lable = new Label(m,i+1,data);
                    sheet.addCell(lable);
                }
            }
        }
        //把创建的内容写入到输出流中,并关闭输出流
        workbook.write();
        workbook.close();
        ouputStream.close();
    }

调用程序,实现页面Execl文件的创建、下载:

 /**
     * 调用程序
     * 此方法属于action,
     */
    public void exportMzDataExcel(){
        OutputStream out = null;

        String userAgent = this.servletRequest.getHeader("USER-AGENT");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
        try {
            String filename = "Execl名称_"+format.format(new Date())+".xls";

            if (userAgent.contains("Firefox")) {
                // 采用BASE64编码
                filename = "=?UTF-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?=";
            } else {
                // 其它浏览器 IE 、google 采用URL编码
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            }
            File file  = new File("D:/shdc/"+format.format(new Date())+"/");
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }
            String url="D:/shdc/"+format.format(new Date())+"/"+filename+"";
            FileOutputStream ouputStream = new FileOutputStream(url);
            this.createMzDataExcel(ouputStream);
            downLoad(url);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

好了,小结到此结束。

所需的jxl.jar包,网上搜索便可得。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

象话

打赏犹如太阳穴的枪口

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值