数据库
首页 > 数据库> > java利用poi解析图片,可以替换图片成XXXXX_X 然后插入回原来数据,将数据插入到数据库

java利用poi解析图片,可以替换图片成XXXXX_X 然后插入回原来数据,将数据插入到数据库

作者:互联网

 @RequestMapping("xxxxxx")
    @ResponseBody
    public BaseResponse downloadWordTitle1(@RequestParam("file") MultipartFile file,
                                           @RequestParam("floorid")String floorid,
                                           @RequestParam("questionbankid")String questionbankid) throws IOException {
        BaseResponse br = new BaseResponse(StatusCode.Success);
        String importPath = "D:\\temp\\temp\\test2.docx";
        File file2 = new File(importPath);
        if(!file2.getParentFile().exists()){
            file2.getParentFile().mkdirs();
        }
        if(!file2.exists()){
            file2.createNewFile();
        }
        writeFile(file.getInputStream(),importPath);
        String resultMsg = "";
        String absolutePath = "";
        try {
            FileInputStream inputStream = new FileInputStream(importPath);
            XWPFDocument xDocument = new XWPFDocument(inputStream);
            List<XWPFParagraph> paragraphs = xDocument.getParagraphs();
            List<XWPFPictureData> pictures = xDocument.getAllPictures();
            Map<String, String> map = Maps.newHashMap();
            String[] tempImagesName = new String[100];
            int tempImagesNameindex = 0;
            for (XWPFPictureData picture : pictures) {
                String id = picture.getPackageRelationship().getId();
                File folder = new File(absolutePath);
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                String rawName = picture.getFileName();
                String fileExt = rawName.substring(rawName.lastIndexOf("."));
                String path = System.getProperty("user.dir");
                path = path.substring(0, path.lastIndexOf("\\") + 1);
                path += "images\\";
                Floor floor = floorService.selectByPrimaryKey(Integer.parseInt(floorid));
                String subjectid = floor.getSubjectid();
                Subject subject = subjectService.selectByPrimaryKey(subjectid);
                String examid = subject.getExamid();
                Exam exam = examService.selectByPrimaryKey(examid);
                String maintypeid = exam.getMaintypeid();
                String questionbanktempid = floor.getQuestionbankid();
                path += maintypeid + "\\" + examid + "\\" + subjectid + "\\" + floorid + "\\";
                String rootPath = path;
                String numberStr = RandomUtils.getRandomNumber(7);
                String imgName = "「" + numberStr + "_" + tempImagesNameindex + "」";
                String newName = "「" + numberStr + "_" + tempImagesNameindex + "」" + fileExt;
                File upload = new File(rootPath);
                if (!upload.exists()) {
                    upload.mkdirs();
                }
                tempImagesName[tempImagesNameindex] = imgName;
                tempImagesNameindex++;
                File saveFile = new File(rootPath + newName);
                @SuppressWarnings("resource")
                FileOutputStream fos = new FileOutputStream(saveFile);
                //写入图片到项目文件夹
                fos.write(picture.getData());
                map.put(id, saveFile.getAbsolutePath());
            }

            String text = "";
            int count = 0;
            int paranum = 1;
            int paraIndex = 0;
            //默认先处理一个文档300道题目

            String[] newresultStr = new String[30000];
            for (XWPFParagraph paragraph : paragraphs) {
                paranum++;
                List<XWPFRun> runs = paragraph.getRuns();
                String textTest = "";
                for (int i = 0; i < runs.size(); i++) {
                    if (runs.get(i).toString().length() == 0) {
                        textTest += tempImagesName[count++];
                    } else {
                        System.out.println("内容:"+runs.get(i).toString());
                        if(runs.get(i).getSubscript().getValue()==2) {
                            textTest += "<sup>"+ runs.get(i).toString()+"</sup>";
                        }
                        else if(runs.get(i).getSubscript().getValue()==3){
                            textTest += "<sub>"+ runs.get(i).toString()+"</sub>";
                        }
                        else{
                            textTest += runs.get(i).toString();
                        }
                        VerticalAlign align = runs.get(i).getSubscript();
                        System.out.println("上角标:"+align.getValue());
                    }
                }
                //这个textTest包含了题干,选项,答案,解析,其中有图片的都可以替换成「XXXXXXX_X」这种格式了
                //录入题目到数据库中去,一般一次性都是录入很多道题目的,因为有引入题库questionbankid,
                //录入后就完成了,然后前端显示,就在题目里增加images列,以逗号隔开[img1],[img2]等等
                // 显示的时候获取显示就好
                String[] resultStr = new String[1000];
                resultStr = textTest.split("\n");
                String[] oldresultStr = new String[1000];
                int countSum = 0;
                for(int i=0;i<resultStr.length;i++){
                    if(resultStr[i].length()>0){
                        oldresultStr[countSum++]=resultStr[i];
                    }
                }
                newresultStr[paraIndex] = oldresultStr[0];
                paraIndex++;
                //所有题目的每一行段落都放置在了newresultStr 字符串数组里了
                //下面循环处理每一行段落
                //处理word模板解析每一个段落
                for (XWPFRun run : runs) {
                    if (run.getCTR().xmlText().indexOf("<w:pict>") != -1) {
                        String runXmlText = run.getCTR().xmlText();
                        int rIdIndex = runXmlText.indexOf("r:id");
                        int rIdEndIndex = runXmlText.indexOf("/>", rIdIndex);
                        String rIdText = runXmlText.substring(rIdIndex, rIdEndIndex);
                        String id = rIdText.split("\"")[1];
                        text = text + "<img src = '" + map.get(id) + "'/>";
                    } else {
                        text = text + run;
                    }
                }

            }
            //先将newresultStr[i]为null的去掉
            String[] newresultStrWithoutNull = new String[30000];
            int countSum = 0;
            for(int i=0;i<paraIndex;i++){
                if(newresultStr[i]!=null){
                    newresultStrWithoutNull[countSum++] = newresultStr[i];
                }
            }
            String[][] titlesInfo = new String[300][1000];
            int titleNumber = 1;
            int perTitleIndex = -1;
            for(int i=0;i<300;i++){
                for(int k=0;k<1000;k++){
                    titlesInfo[i][k]="";
                }
            }
            for(int i=0;i<countSum;i++){
                if(newresultStrWithoutNull[i].startsWith("【题型】")){
                    perTitleIndex++;  //遇到有【】才需要新开一个字符串
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【题型】".length(),newresultStrWithoutNull[i].length());
                }else
                if(newresultStrWithoutNull[i].startsWith("【题干】")){
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【题干】".length(),newresultStrWithoutNull[i].length());
                }else
                if(newresultStrWithoutNull[i].startsWith("【A】")){
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【A】".length(),newresultStrWithoutNull[i].length());
                }else
                if(newresultStrWithoutNull[i].startsWith("【B】")){
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【B】".length(),newresultStrWithoutNull[i].length());
                }/*else
                if(newresultStrWithoutNull[i].startsWith("【C】")){
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【C】".length(),newresultStrWithoutNull[i].length());
                }else
                if(newresultStrWithoutNull[i].startsWith("【D】")){
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【D】".length(),newresultStrWithoutNull[i].length());
                }else
                if(newresultStrWithoutNull[i].startsWith("【E】")){
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【E】".length(),newresultStrWithoutNull[i].length());
                }else
                if(newresultStrWithoutNull[i].startsWith("【F】")){
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【F】".length(),newresultStrWithoutNull[i].length());
                }*/else
                if(newresultStrWithoutNull[i].startsWith("【答案】")){
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【答案】".length(),newresultStrWithoutNull[i].length());
                }else
                if(newresultStrWithoutNull[i].startsWith("【解析】")){
                    //遇到解析说明一道题目解析完毕,进入下一道题目的循环
                    perTitleIndex++;
                    titlesInfo[titleNumber][perTitleIndex]=newresultStrWithoutNull[i].substring("【解析】".length(),newresultStrWithoutNull[i].length());
                    //遇到解析设置完题目,如果下一条信息是以"【"打头,则此题结束,重新置0,
                    if(newresultStrWithoutNull[i+1]!=null&&newresultStrWithoutNull[i+1].startsWith("【")) {
                        perTitleIndex = -1;
                        titleNumber++;
                    }
                }else{
                    titlesInfo[titleNumber][perTitleIndex]+=newresultStrWithoutNull[i];
                    titleNumber++;
                    perTitleIndex=-1;
                    System.out.println("题目增加了一道:"+titleNumber);
                }
            }
            Date date = new Date();
            String time = getFisrtDayOfMonth(date);
            String idsts = getIdstrs(time);
            char c1 = (char) (int) (Math.random() * 26 + 97);
            char c2 = (char) (int) (Math.random() * 26 + 97);
            char c3 = (char) (int) (Math.random() * 26 + 97);
            char c4 = (char) (int) (Math.random() * 26 + 97);
            char c5 = (char) (int) (Math.random() * 26 + 97);
            char c6 = (char) (int) (Math.random() * 26 + 97);
            Floor floor = floorService.selectByPrimaryKey(Integer.parseInt(floorid));
            floor.setTitlenumber(floor.getTitlenumber()+titleNumber);
            String subjectid = floor.getSubjectid();
            int Flagg = floorService.updateByPrimaryKeySelective(floor);
            if(Flagg > 0){
                resultMsg +="更新floor题目数量成功!";
            }
            Questionbank questionbank = questionBankService.selectByPrimaryKey(floor.getQuestionbankid());
            if (questionbank != null) {
                questionbank.setTitlenumber(questionbank.getTitlenumber()+titleNumber);
                questionbank.setUpdatetime(new Date());
                //这个到时候要自己更改
                questionbank.setSubjectid(subjectid);
                Flagg = questionBankService.updateByPrimaryKeySelective(questionbank);
                if(Flagg > 0){
                    resultMsg +="插入题库部分数据成功!";
                }
            }
            else{
                questionbank = new Questionbank();
                questionbank.setSubjectid(subjectid);
                questionbank.setTypenumber(titleNumber);
                questionbank.setQuestionbankid(floor.getQuestionbankid());
                questionbank.setUpdatetime(new Date());
                questionbank.setCreatetime(new Date());
                questionbank.setTypenumber(0);
                Flagg = questionBankService.insert(questionbank);
                if(Flagg > 0){
                    resultMsg +="新建题库,并且插入题库部分数据成功!";
                }
            }

            Title title = new Title();
            System.out.println("题目数量:"+titleNumber);
            for(int k=1;k<=titleNumber;k++){
                int flag = 0;
                int optionNumber = 1;
                date = new Date();
                time = getFisrtDayOfMonth(date);
                idsts = getIdstrs(time);
                c1 = (char) (int) (Math.random() * 26 + 97);
                c2 = (char) (int) (Math.random() * 26 + 97);
                c3 = (char) (int) (Math.random() * 26 + 97);
                c4 = (char) (int) (Math.random() * 26 + 97);
                c5 = (char) (int) (Math.random() * 26 + 97);
                c6 = (char) (int) (Math.random() * 26 + 97);
                String titleid = idsts + c1+c2+c3+c4+c5+c6;
                title.setTitleid(titleid);
                for(int i=0;i<1000;i++) {
                    if (!titlesInfo[k][i].equals("")) {
                        if(i==0){
                            title.setTitletypealias(titlesInfo[k][i]);
                            //提醒导入分类在这里设置
                            if(titlesInfo[k][i].startsWith("判断题")){
                                System.out.println("判断题");
                                title.setTitletype("5");
                            }
                        }
                        if(i==1){
                            title.setStem(titlesInfo[k][i]);
                        }
                        if(i==2){
                            Option option = new Option();
                            date = new Date();
                            time = getFisrtDayOfMonth(date);
                            idsts = getIdstrs(time);
                            c1 = (char) (int) (Math.random() * 26 + 97);
                            c2 = (char) (int) (Math.random() * 26 + 97);
                            c3 = (char) (int) (Math.random() * 26 + 97);
                            c4 = (char) (int) (Math.random() * 26 + 97);
                            c5 = (char) (int) (Math.random() * 26 + 97);
                            c6 = (char) (int) (Math.random() * 26 + 97);
                            String optionid = idsts + c1 + c2 + c3 + c4 + c5 + c6;
                            option.setOptionid(optionid);
                            option.setCreatetime(new Date());
                            option.setUpdatetime(new Date());
                            option.setOptionnumber(optionNumber);
                            option.setOptionvalue(titlesInfo[k][i]);
                            option.setTitleid(titleid);
                            Flagg = optionService.insert(option);
                            if(Flagg > 0){
                                resultMsg +="插入Option A一条数据成功!";
                            }
                            optionNumber++;
                            try {
                                Thread.sleep(800);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        if(i==3){
                            Option option = new Option();
                            date = new Date();
                            time = getFisrtDayOfMonth(date);
                            idsts = getIdstrs(time);
                            c1 = (char) (int) (Math.random() * 26 + 97);
                            c2 = (char) (int) (Math.random() * 26 + 97);
                            c3 = (char) (int) (Math.random() * 26 + 97);
                            c4 = (char) (int) (Math.random() * 26 + 97);
                            c5 = (char) (int) (Math.random() * 26 + 97);
                            c6 = (char) (int) (Math.random() * 26 + 97);
                            String optionid = idsts + c1 + c2 + c3 + c4 + c5 + c6;
                            option.setOptionid(optionid);
                            option.setCreatetime(new Date());
                            option.setUpdatetime(new Date());
                            option.setOptionnumber(optionNumber);
                            option.setOptionvalue(titlesInfo[k][i]);
                            option.setTitleid(titleid);
                            Flagg = optionService.insert(option);
                            if(Flagg > 0){
                                resultMsg +="插入Option B一条数据成功!";
                            }
                            optionNumber++;
                            try {
                                Thread.sleep(800);//休眠一分钟,避免option创建乱序问题
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        if(i==4){
                            title.setOriginanswer(titlesInfo[k][i]);
                            Answer answer = new Answer();
                            date = new Date();
                            time = getFisrtDayOfMonth(date);
                            idsts = getIdstrs(time);
                            c1 = (char) (int) (Math.random() * 26 + 97);
                            c2 = (char) (int) (Math.random() * 26 + 97);
                            c3 = (char) (int) (Math.random() * 26 + 97);
                            c4 = (char) (int) (Math.random() * 26 + 97);
                            c5 = (char) (int) (Math.random() * 26 + 97);
                            c6 = (char) (int) (Math.random() * 26 + 97);
                            String answerid = idsts + c1 + c2 + c3 + c4 + c5 + c6;
                            answer.setAnswerid(answerid);
                            answer.setAnswervalue(titlesInfo[k][i]);
                            answer.setTitleid(titleid);
                            answer.setUpdatetime(new Date());
                            answer.setCreatetime(new Date());
                            Flagg = answerService.insert(answer);
                            if(Flagg > 0){
                                resultMsg +="插入答案一条数据成功!";
                            }
                        }
                        if(i==5){
                            Analyse analyse = new Analyse();
                            date = new Date();
                            time = getFisrtDayOfMonth(date);
                            idsts = getIdstrs(time);
                            c1 = (char) (int) (Math.random() * 26 + 97);
                            c2 = (char) (int) (Math.random() * 26 + 97);
                            c3 = (char) (int) (Math.random() * 26 + 97);
                            c4 = (char) (int) (Math.random() * 26 + 97);
                            c5 = (char) (int) (Math.random() * 26 + 97);
                            c6 = (char) (int) (Math.random() * 26 + 97);
                            String analyseid = idsts + c1 + c2 + c3 + c4 + c5 + c6;
                            analyse.setAnalyseid(analyseid);
                            analyse.setAnalysevalue(titlesInfo[k][i]);
                            analyse.setTitleid(titleid);
                            analyse.setUpdatetime(new Date());
                            analyse.setCreatetime(new Date());
                            Flagg = analyseService.insert(analyse);
                            if(Flagg > 0){
                                resultMsg +="插入解析一条数据成功!";
                            }
                        }
                    }
                }
                title.setCreatetime(new Date());
                title.setOptionnumber(optionNumber-1);
                title.setQuestionbankid(questionbankid);
                title.setTitlescore(5.0);
                title.setUpdatetime(new Date());
                Flagg = titleService.insert(title);
                if(Flagg > 0){
                    resultMsg+= "插入第"+k+"道题目成功!\n";
                }
                List<Intofloortime> lists = intofloortimeService.selectByFloorid(Integer.parseInt(floorid));
                for(int i=0;i<lists.size();i++) {
                    lists.get(i).setNumbertime(0);
                    Flagg =intofloortimeService.updateIntofloortime(lists.get(i));
                    if(Flagg >0){
                        resultMsg+= "更新第Floorid=("+floorid+")--->InfoFloorTime表成功!\n";
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return br;
    }

word文档格式

 

 其中一个可以设置X^K 设置k上角标内容,这一个花了我至少5个小时去思考。

              for (int i = 0; i < runs.size(); i++) {
                    if (runs.get(i).toString().length() == 0) {
                        textTest += tempImagesName[count++];
                    } else {
                        System.out.println("内容:"+runs.get(i).toString());
                        if(runs.get(i).getSubscript().getValue()==2) {
                            textTest += "<sup>"+ runs.get(i).toString()+"</sup>";
                        }
                        else if(runs.get(i).getSubscript().getValue()==3){
                            textTest += "<sub>"+ runs.get(i).toString()+"</sub>";
                        }
                        else{
                            textTest += runs.get(i).toString();
                        }
                        VerticalAlign align = runs.get(i).getSubscript();
                        System.out.println("上角标:"+align.getValue());
                    }
                }

  

标签:runs,java,String,int,26,插入,new,Math,图片
来源: https://www.cnblogs.com/EarlyBridVic/p/13087038.html