利用jxl实现excel导出

来源:互联网 发布:股票历史集合竞价数据 编辑:程序博客网 时间:2024/05/19 19:32

【说明】

1.点击导出,取前台现有的数据通过ajax传到后台,

2.通过jxl生成服务器上的xls文件

3.ajax成功之后转到download,也就是打开保存界面:


【配置】

1.使用了struts2的注解配置


【代码】

jsp:

//导出    $('#exportBtn').click(function(){var str = '';    $('div.datagrid-view2 table.datagrid-btable').find('td').each(function(){str += $(this).text() + '%%%%';});        $.ajax({url : 'scoreAction!exportExcel.action',type : 'POST',data : {str : str,fileName : 'score.xls'},dataType : 'json'    }).done(function(data){    if(data && data == 'success'){    window.location.href = "scoreAction!downloadFile.action?fileName=score.xls";    }else{    $.messager.show({title : '失败',msg : '导出失败!'});    }    }).fail(function(){    $.messager.show({title : '失败',msg : '导出失败!'});    });    });

action:

action中添加字段fileName和它的setter,getter

添加一个方法getInputStream(),

添加注解,部分代码如下:

@Action(value = "scoreAction", results = { @Result(name = "download", type="stream",params={            "contentType","application/octet-stream",            "inputName","inputStream",            "contentDisposition","attachment;filename=${fileName}",            "bufferSize","4096"                })})public class ScoreAction extends BaseAction implements ModelDriven<ClazzRlLearnerPage> {@Autowiredprivate ScoreServiceI scoreService;private String fileName;private String str;//method--publicpublic void exportExcel(){writeJson(scoreService.exportExcel(str));}public String downloadFile(){return "download";}public InputStream getInputStream(){InputStream is = null;String filePath = ((ServletContext)ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT)).getRealPath("/") + "jsp\\score\\xls\\score.xls";try {is = new FileInputStream(new File(filePath));} catch (FileNotFoundException e) {e.printStackTrace();}return is;}//getters and setterspublic String getStr() {return str;}public void setStr(String str) {this.str = str;}public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}}

jxl实现导出excel:

//导出Excelpublic String exportExcel(String str){WritableWorkbook wwb;String[] strs = str.split("%%%%");String path = ((ServletContext)ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT)).getRealPath("/");        try {          //创建excel            wwb = Workbook.createWorkbook(new FileOutputStream(path + "jsp\\score\\xls\\score.xls"));            //创建格式            WritableCellFormat wcf = new WritableCellFormat();            wcf.setVerticalAlignment(VerticalAlignment.CENTRE);            wcf.setAlignment(Alignment.CENTRE);                        //创建sheet            WritableSheet ws = wwb.createSheet("sheet", 0);            ws.setRowView(1, 500);                        //表头            ws.addCell(new Label(0, 0, "序号", wcf));            ws.addCell(new Label(1, 0, "机构", wcf));            ws.addCell(new Label(2, 0, "班级", wcf));            ws.addCell(new Label(3, 0, "课件信息", wcf));            ws.addCell(new Label(4, 0, "学员姓名", wcf));            ws.addCell(new Label(5, 0, "课件成绩", wcf));            ws.addCell(new Label(6, 0, "作业成绩", wcf));            ws.addCell(new Label(7, 0, "总成绩", wcf));                        //内容            int col = 0;            int row = 1;            for (int i = 0; i < strs.length; i++) {            if(i == 0) ws.addCell(new Label(col++, row, row+"", wcf));            ws.addCell(new Label(col++, row, strs[i], wcf));            if((i+1)%7 == 0){            col = 0;            row++;            if((i+1) != strs.length) ws.addCell(new Label(col++, row, row+"", wcf));            } }            wwb.write();            wwb.close();                        return "success";        } catch (Exception e){        e.printStackTrace();                return "fail";        }}