日期:2014-05-19  浏览次数:20651 次

如何在jsp中吧动态生成的数据导入excel
我通过后台action生成的数据在jsp中遍历放到table
现在要在jsp中通过一个button 然后可以吧数据保存到本地生成excel文件
我开始用js做一直报错,后来想通过button吧table的数据发送到servlet然后经过处理再打包回传下载,这个可行性高吗?
或者各位还有什么方法,求教谢谢

------解决方案--------------------
给你一段参考代码,java写入excel文件的
这是我的项目里的一段查询记录并且下载成excel的.

通过在后台查询出一个list,然后写入excel,供用户下载 , 这个应该可以满足你的需求
需要用到的jar包自己百度


Java code


public void ghhzExcel(HttpServletResponse response,String t1,String t2){
        ModelAndView mav = new ModelAndView();
        String date = dus.showDate("yyyy-MM-dd");
        List<Mzguahao> ghdlist = gs.queryGhd(t1, t2);
        float heji =0;
        if(ghdlist.size()>0)
        {
            for(int i=0;i<ghdlist.size();i++)
            {
                heji +=Float.parseFloat(ghdlist.get(i).getSfhj());
            }
        }
        String filename="门诊收费挂号单查询"+date+".xls";
        try {
             response.setContentType("APPLICATION/OCTET-STREAM");   
             response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
             OutputStream os = response.getOutputStream();
            jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os);
            jxl.write.WritableSheet ws = wwb.createSheet("Sheet1", 0);
            String[] title = {"处方编号","缴费标志","患者类型","患者姓名","性别","年龄","单位","挂号科室","医生","划价时间"};
            for(int i= 1;i<(ghdlist.size()+1);i++){
                String[] content = {ghdlist.get(i-1).getGhnum(),ghdlist.get(i-1).getBz(),ghdlist.get(i-1).getHztype(),ghdlist.get(i-1).getName(),ghdlist.get(i-1).getSex(),ghdlist.get(i-1).getAge(),ghdlist.get(i-1).getJob(),ghdlist.get(i-1).getKeshi(),ghdlist.get(i-1).getDoctor(),ghdlist.get(i-1).getGhdate()};
                for(int j=0;j<10;j++){
                    jxl.write.Label labelB= new jxl.write.Label(j,0,title[j]);
                    ws.addCell(labelB);
                    jxl.write.Label labelC = new jxl.write.Label(j,i,content[j]);
                    ws.addCell(labelC);
                }                
            }
            jxl.write.Label label1= new jxl.write.Label(0,ghdlist.size()+1,"合计");
            jxl.write.Label label2= new jxl.write.Label(1,ghdlist.size()+1,String.valueOf(heji));
            ws.addCell(label1);
            ws.addCell(label2);
            wwb.write();
            wwb.close();
            os.flush();
            os.close();