java使用jxl生成并下载excel

java | 2019-09-13 10:02:39

java使用jxl生产并下载excel的案例,并解决了乱码问题,本程序的目的好处就是不在服务器生产excel文件,当然你想在服务器生成excel文件存档,直接加一句代码就可以 了,这里就不多说了,没有jxl jar包的可以自己在网上下载

public void doPost(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                        request.setCharacterEncoding("utf-8");
                response.setContentType("texthtml;charset=utf-8");
                OutputStream myout=response.getOutputStream();
                WritableWorkbook wb =Workbook.createWorkbook(myout);
                try {
                        WritableSheet sheet=wb.createSheet("器官捐献志愿者统计表", 0);
                        
                        设置表头
                        Label label=null;
                        label =new Label(0, 0, "编号");
                        sheet.addCell(label);
                        label =new Label(1, 0, "姓名");
                        sheet.addCell(label);
                        label =new Label(6, 0, "年龄");
                        sheet.addCell(label);
                        label =new Label(7, 0, "性别");
                        sheet.addCell(label);
                        label =new Label(8, 0, "籍贯");
                        sheet.addCell(label);
                        看到这里你应该都懂了,是的你可以在这里加入更多的数据
                        
                        response.setContentType("applicationoctet-stream;charset=UTF-8");
                        String name = "统计表.xls";
                        String userAgent = request.getHeader("User-Agent").toLowerCase();  
                        byte[] bytes = userAgent.contains("safari") ?name.getBytes("UTF-8"):name.getBytes("gbk");  name.getBytes("UTF-8")处理safari的乱码问题  
                        name = new String(bytes, "ISO-8859-1");  各浏览器基本都支持ISO编码  
                        response.setHeader("Content-disposition", String.format("attachment;filename=\"%s\"", name));
                        wb.write();
                } catch (Exception e) {
                         TODO Auto-generated catch block
                        e.printStackTrace();
                }finally{
                         try {
                                wb.close();
                                myout.close();
                        } catch (WriteException e) {
                                 TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                         
                }                
                        
        }




登录后即可回复 登录 | 注册
    
关注编程学问公众号