生成二维码,excel

 

1.生成二维码

 1 /**
 2      * 生成二维码  二维码跳转到答题界面
 3      * @return
 4      */
 5     @Action("makeQcode")
 6     public void makeQcode(){
 7         json.put("success", true);
 8         try {
 9             String filePath = super.getRealPath("static/server-image");
10             log.info("filePath"+filePath);
11             String fileName = surveyId+".png"; 
12             File file =new File(filePath+"/"+fileName);
13             File fileDir = new File(filePath);
14             if(!fileDir.exists()){ //     不存在 
15                 //先得到文件的上级目录,并创建上级目录,在创建文件
16                 fileDir.mkdirs();
17                }
18             if(file.exists()){
19                 file.delete();
20             }
21             String text = super.loadServerPath()+"/frontAdmin/receptionSurvey-index.action?surveyId="+surveyId;
22             String photoType=super.getSession().getServletContext().getRealPath("static/server-image")+"\\"+fileName;
23             log.info("photoType:"+photoType);
24             log.info("text:"+text);
25             ImageIO.write(qRCodeCommon(text,"png",11,photoType), "png", file);
26             json.put("path", super.loadServerPath()+"/static/server-image/"+fileName);
27         } catch (Exception e) {
28             e.printStackTrace();
29             throw new ProjectException(e.getMessage());
30         }  
31         super.printToJson(json.toString());
32     }
View Code
1 public String getRealPath(String str) {
2         return ServletActionContext.getServletContext().getRealPath(str);
3     }
View Code
 1 /**
 2         * 生成二维码(QRCode)图片的公共方法
 3         * 
 4         * @param content
 5         *            存储内容
 6         * @param imgType
 7         *            图片类型
 8         * @param size
 9         *            二维码尺寸
10         * @return
11         */
12        public static BufferedImage qRCodeCommon(String content, String imgType, int size,String imageFrom) {
13            BufferedImage bufImg = null;
14            try {
15                Qrcode qrcodeHandler = new Qrcode();
16                // 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
17                qrcodeHandler.setQrcodeErrorCorrect('M');
18                qrcodeHandler.setQrcodeEncodeMode('B');
19                // 设置设置二维码尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大
20                qrcodeHandler.setQrcodeVersion(size);
21                // 获得内容的字节数组,设置编码格式
22                byte[] contentBytes = content.getBytes("utf-8");
23                // 图片尺寸
24                int imgSize = 67 + 12 * (size - 1) + 16;
25                bufImg = new BufferedImage(imgSize, imgSize,
26                        BufferedImage.TYPE_INT_RGB);
27                Graphics2D gs = bufImg.createGraphics();
28                // 设置背景颜色
29                gs.setBackground(Color.WHITE);
30                gs.clearRect(0, 0, imgSize, imgSize);
31 
32                // 设定图像颜色> BLACK
33                gs.setColor(Color.BLACK);
34                // 设置偏移量,不设置可能导致解析出错
35                int pixoff = 10;
36                // 输出内容> 二维码
37                if (contentBytes.length > 0 && contentBytes.length < 800) {
38                    boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
39                    for (int i = 0; i < codeOut.length; i++) {
40                        for (int j = 0; j < codeOut.length; j++) {
41                            if (codeOut[j][i]) {
42                                gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
43                            }
44                        }
45                    }
46                } else {
47                    throw new Exception("QRCode content bytes length = "
48                            + contentBytes.length + " not in [0, 800].");
49                }
50                /* 判断是否需要添加logo图片 */  
51             if(true){  
52                 int width_4 = 200 / 4;  
53                 int width_8 = width_4 / 2;  
54                 int height_4 = 200 / 4;  
55                 int height_8 = height_4 / 2;  
56                 Image img = ImageIO.read(new File(imageFrom));  
57                 gs.drawImage(img, width_4 + width_8, height_4 + height_8,width_4,height_4, null);  
58                 gs.dispose();    
59                 bufImg.flush();  
60             } 
61                gs.dispose();
62                bufImg.flush();
63            }catch (IIOException e) {
64 //            log.info("Error:"+"javax.imageio.IIOException: Can't read input file!");
65         } catch (Exception e) {
66                e.printStackTrace();
67            }
68            return bufImg;
69        }
View Code
/**
     * 获取serverPath
     * @return
     */
    protected String loadServerPath(){
        HttpServletRequest request = this.getRequest();
        String contextPath = this.loadContextPath();
        String serverName = request.getServerName();
        if(serverName.indexOf("xxxxx.com")>=0 ){
            return "https://"+serverName+contextPath;
        }else if(serverName.indexOf(":8080")>=0 || serverName.indexOf("localhost")>=0){
            return "http://localhost:8080"+contextPath;
        }else{
            return "https://"+serverName+contextPath;
        }
    }

 

 

2.导出excel

只要文件保存的路径,文件名,表中的标题数组,表中的内容这四个,,其中的标题名和list的key要一致

String relativePath = "static/Excel";
                String filePath = super.getRealPath(relativePath);
                log.info("filePath:"+filePath);
                String fileName = super.date2string(new Date(), "yyyyMMddHHmmss"); 
                log.info("filePath"+filePath);

String[] column={"问卷名称","问卷类型","用户openId","题目名称","题目类型"
                                ,"选项内容","用户分数","参与时间","用户名","用户手机号"};
                        if(surveyQuestionList != null && surveyQuestionList.size()>0){
                            for(int j=0;j<surveyQuestionList.size();j++){
                                Map<String, Object> map=new HashMap<String, Object>();
                                JSONObject questionJson=JSONObject.fromObject(surveyQuestionList.get(j));
                                if(j==0){
                                    map.put("问卷名称", surveyAnswer.getSurveyTitle()+"");
                                    map.put("问卷类型", "计分类型");
                                    map.put("用户openId", surveyAnswer.getOpenId()+"");
                                }else{
                                    map.put("问卷名称", "");
                                    map.put("问卷类型", "");
                                    map.put("用户openId", "");
                                }
                                
                                map.put("题目名称", questionJson.get("questionName")+"");
                                if("single".equals(questionJson.get("questionType")+"")){
                                    map.put("题目类型", "单选题");
                                }else if("multiple".equals(questionJson.get("questionType")+"")){
                                    map.put("题目类型", "多选题");
                                }
                                
                                JSONArray optionNameJson=JSONArray.fromObject(questionJson.get("optionName"));
                                if(optionNameJson != null && optionNameJson.size()>0){
                                    String optName="";
                                    for(int k=0;k<optionNameJson.size();k++){
                                        if(k==optionNameJson.size()-1){
                                            optName+=optionNameJson.get(k);
                                        }else{
                                            optName+=optionNameJson.get(k)+",";
                                        }
                                    }
                                    map.put("选项内容", optName+"");
                                }
                                
                                if(j==0){
                                    map.put("用户分数", surveyAnswer.getScore()+"");
                                    map.put("参与时间", surveyAnswer.getInsertTime()+"");
                                }else{
                                    map.put("用户分数", "");
                                    map.put("参与时间", "");
                                }
                                map.put("用户名", "".equals((surveyAnswer.getName()+"").trim())?"未填写用户名":surveyAnswer.getName()+"");
                                map.put("用户手机号", "".equals((surveyAnswer.getMobile()+"").trim())?"未填写手机号":surveyAnswer.getMobile()+"");
                                list.add(map);
                            }
                        }

                        super.createExcel(relativePath, fileName, column, list);

 

/**
     * 生成报表
     * @param path
     * @param fileName
     * @param column
     * @param list
     * @return
     */
    public String createExcel(String path,String fileName,String[] column,List<Map<String, Object>> list){
        
        String urlPath = path;
        path = this.getRealPath(path);
        
        log.info("urlPath:"+urlPath);
        log.info("path:"+path);
        
        if(!path.endsWith("/")){
            path = path + "/";
        }
        
        if(!urlPath.endsWith("/")){
            urlPath = urlPath + "/";
        }
        String downloadPath = path +fileName+".xls";
        log.info("downloadPath:"+downloadPath);
        //创建HSSFWorkbook对象  
        HSSFWorkbook wb = new HSSFWorkbook();  
        //创建HSSFSheet对象  
        HSSFSheet sheet = wb.createSheet("DATA");  
        //创建HSSFRow对象  
        HSSFRow row = sheet.createRow(0); //第一行
        //
        for (int i = 0; i < column.length; i++) {
            row.createCell(i).setCellValue(column[i]);
        }
        
        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow(i+1);
            Map<String, Object> map = list.get(i);
            for (int j = 0; j < column.length; j++) {
                row.createCell(j).setCellValue((String)map.get(column[j]));
            }
        }
        
        //输出Excel文件  
        FileOutputStream output;
        try {
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            
            File csv = new File(downloadPath);
            if(csv.exists()){
                csv.delete();
            }
            output = new FileOutputStream(csv);
            wb.write(output);
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }  
        String  rv = urlPath+fileName+".xls";
        log.info("rv:"+rv);
        return rv;
    }

 

posted on 2018-01-30 15:17  老板我要两份黄焖鸡  阅读(175)  评论(0编辑  收藏  举报