• internship:利用EasyPoi 读取word文档生成JavaBean


    基于对SSM框架的掌握之后,继而对springboot的搭建 。
    初始的工作就是对重装系统的电脑进行所有的环境配置 及其之后对常用框架的搭建。之后对springboot框架的持续学习。
    环境搭建完成之后的内容,就是——
    1、熟悉使用EasyPoi工具
    2、使用EasyPoi读取以上两个文档的内容
    3、获取文档中"{{}}"包裹的变量名并生成Java文件,例如Model.java

    Model.java:

    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    import lombok.experimental.Accessors;
    
    import java.math.BigDecimal;
    import java.time.LocalDate;
    
    /**
     * 预算调整报告数据
     */
    @Data
    @Accessors(chain = true)
    public class BudgetAdjustDeptReportModel {
    
        @ApiModelProperty(value = "年度")
        private int year = LocalDate.now().getYear();
    
        @ApiModelProperty(value = "部门")
        private String dept = "-";
    
        @ApiModelProperty(value = "季度")
        private String quarter;
    	
    	@ApiModelProperty(value = "季度")
        private BigDecimal ybggIncome;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    接下来就是持续了解 部分掌握easyPoi工具——
    前端传递参数,接受返回的文件并下载到本地
    后端:接受传递过来的参数,查找出对应的实体类,通过easypoi提供的模板和控制类,写入文件
    模板:根据要写入的值确定word模板,并将其放入启动类所在包的resource下,这里的模板,就联想到
    thymeleaf模板。
    实体:实体类添加@Escel相关注释

    确定word文档模板:

    {{area}}   双括号内放变量或常量
    {{fd:(Time;yyyy-MM-dd)}}   fd:(obj;yyyy-MM-dd)格式化时间格式
    {{fe:List t}}   fe:obj  t  t为别名
    
    • 1
    • 2
    • 3

    为了提取word文档的指定内容 利用了字符串的截取及其替代——replaceAll的参数是regex,即基于正则表达式的替换,比如,可以通过replaceAll(“\d”, “*”)把一个字符串所有的数字字符都换成星号;replaceAll是一个非常好用的方法 基于正则表达式的运用能更好的实现提取。同时需要注意的是 一些被替代的需要转义字符的使用。
    比如:

      sub = sub.replaceAll("[^a-z^A-Z]", "");
    
    • 1
    "[^a-z^A-Z]" 表示非英文字母的
    
    • 1

    表示提取纯英文。

    第一份任务安排是读取word文档 自动生成JavaBean
    .docx:
    在这里插入图片描述
    其中 字段信息不仅于此;所以手动去创建类及属性 并不实际:
    编写类实现自动生成:

    package com.boot.demo.output;
    
    import com.boot.demo.service.EntityProperty;
    import com.boot.demo.service.FieldProperty;
    import com.boot.demo.service.ParseConfig;
    import com.boot.demo.service.WordPOI;
    import org.apache.poi.ooxml.POIXMLDocument;
    import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
    import org.apache.poi.openxml4j.opc.OPCPackage;
    import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class WordPoiImpl {
        public static void main(String[] args) throws IOException {
           WordPOI wordPOI=new WordPOI();
           String BigDecimal="BigDecimal";
            List<String> list = new ArrayList<>();
            List<FieldProperty> fieldProperties=new ArrayList<>();
            ParseConfig parseConfig=new ParseConfig();
    
            try {
                OPCPackage opcPackage = POIXMLDocument.openPackage("C:\\Users\\Redic\\IdeaProjects\\demo\\src\\main\\resources\\word\\ystz.docx");
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                String text2007 = extractor.getText();
                String str1=text2007.replaceAll("\\{\\{","}}");
                String subSentences[] = str1.split("\\}\\}");
                String allStr="";
    
                for (String sub : subSentences) {
                    sub=sub.replaceAll("[^a-z^A-Z]", "");
                    allStr+=sub+" ";
                }
                String subNew[]=allStr.split(" ");
    
    
                for (String no:subNew) {
                    if(!no.isEmpty())
                        list.add(no);
                }
    
                for (int i = 0; i < list.size(); i++) {
                    for (int j = i+1; j <list.size() ; j++) {
                        if (list.get(i).equals(list.get(j)))
                            list.remove(i);
                    }
                }
    
    //            Iterator it = list.iterator();测试是否 去除
    //            while (it.hasNext()) {
    //                System.out.println(it.next());
    //            }
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            FieldProperty fieldProperty1=new FieldProperty(list.get(0),"int");
            fieldProperties.add(fieldProperty1);
            fieldProperties.add(new FieldProperty(list.get(1),"String"));
            for(int i=2;i<list.size();i++)
            {
            fieldProperties.add(new FieldProperty(list.get(i),BigDecimal));
            }
    
            EntityProperty entityProperty=new EntityProperty("com.boot.demo.pojo","BudgetAdjustDeptReportModel",fieldProperties);
    
            wordPOI.generateEntity(entityProperty,false,"C:\\Users\\Redic\\IdeaProjects\\demo\\src\\main\\java\\com\\boot\\demo\\pojo",parseConfig);
            
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    FieldProperty:

    package com.boot.demo.service;
    
    /**
     * 字段属性
     */
    public class FieldProperty {
    
        /**
         * 字段名称设置
         */
        private String name;
    
        /**
         * 字段类型设置
         */
        private String type;
        /**
         * 注释说明中文
         */
        private String desc;
    
        public FieldProperty()
        {
    
        }
        public FieldProperty(String name, String type) {
            this.name = name;
            this.type = type;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public void setDesc(String desc) {
            this.desc = desc;
        }
    
        @Override
        public String toString() {
            return "FieldInfo{" +
                    "name='" + name + '\'' +
                    ", type=" + type +
                    ", desc='" + desc + '\'' +
                    '}';
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    EntityProperty:

    package com.boot.demo.service;
    
    import java.util.List;
    
    /**
     * 实体属性
     * @author <a href="mailto:jenly1314@gmail.com">Jenly</a>
     */
    public class EntityProperty {
    
        private String packageName;
    
        private String className;
    
        private List<FieldProperty> filedPropertyList;//字段属性集合
    
    
        public EntityProperty() {
    
        }
    
        public EntityProperty(String packageName, String className) {
            this.packageName = packageName;
            this.className = className;
        }
    
        public EntityProperty(String packageName, String className, List<FieldProperty> filedPropertyList) {
            this.packageName = packageName;
            this.className = className;
            this.filedPropertyList = filedPropertyList;
    
        }
    
        public String getPackageName() {
            return packageName;
        }
    
        public void setPackageName(String packageName) {
            this.packageName = packageName;
        }
    
        public String getClassName() {
            return className;
        }
    
        public void setClassName(String className) {
            this.className = className;
        }
    
        public List<FieldProperty> getFiledPropertyList() {
            return filedPropertyList;
        }
    
        public void setFiledPropertyList(List<FieldProperty> filedPropertyList) {
            this.filedPropertyList = filedPropertyList;
        }
    
        @Override
        public String toString() {
            return "EntityProperty{" +
                    "packageName='" + packageName + '\'' +
                    ", className='" + className + '\'' +
                    ", filedPropertyList=" + filedPropertyList +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    wordPOI:

    public  void generateEntity(EntityProperty entityProperty, boolean isDoc, String outPath,ParseConfig parseConfig) throws IOException{
            String className = entityProperty.getClassName();
            String javaName =  className + ".java";
    
            StringBuffer buffer = new StringBuffer();
    
            buffer.append("package "+ entityProperty.getPackageName()+";\n\n");
            //是否使用Lobmok
            boolean useLombok = parseConfig.isUseLombok();
            //是否生成get和set方法
            boolean genGetterAndSetter = parseConfig.isGenGetterAndSetter();
            //是否生成toString方法
            boolean genToString = parseConfig.isGenToString();
    
            //是否包含泛型
            boolean genericity = false;
            //是否导入List
            boolean importList = false;
            //是否导入Set
            boolean importBigDecimal = true;
            //是否导入Map
            boolean importMap = false;
    
            List<FieldProperty> filedPropertyList = entityProperty.getFiledPropertyList();
            if(filedPropertyList !=null ){
    
                StringBuffer bufferField = new StringBuffer();
                StringBuffer bufferGetSet = new StringBuffer();
                StringBuffer bufferToString = new StringBuffer();
    
                //toString开头
                if(genToString && !useLombok){
                    bufferToString.append("\t@Override\n")
                            .append("\tpublic String toString(){\n")
                            .append("\t\treturn ")
                            .append("\"").append(className).append("{\" + \n");
                }
    
                int index = 0;
                int size =  filedPropertyList.size();
                for(FieldProperty filedProperty : filedPropertyList){
                    bufferField.append("\t/** " + filedProperty.getDesc() + " */\n");
                    bufferField.append("\tprivate " + filedProperty.getType() + " " + filedProperty.getName() + ";\n");
    
                    String fieldType = filedProperty.getType();
                    if(fieldType!=null){
                        //遍历是否包含泛型
                        if(fieldType.contains("<T>") || fieldType.equals("T")){
                            genericity = true;
                        }
    
                        //遍历是否包含集合
                        if(fieldType.startsWith("List")){
                            importList = true;
                        }else if(fieldType.startsWith("Set")){
                            importBigDecimal = true;
                        }else if(fieldType.startsWith("Map")){
                            importMap = true;
                        }
    
                    }
    
                    if(!useLombok){//只有当不使用Lombok时,才会根据genGetterAndSetter 和 genToString 来判断是否生成get、set、toString等方法
    
                        String fieldName = filedProperty.getName();
                        //是否生成get和set方法
                        if(genGetterAndSetter){
                            String getterName = fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
    
                            //Generate getter
                            if("boolean".equalsIgnoreCase(fieldType)){
                                bufferGetSet.append("\tpublic " + fieldType + " is" + getterName + "(){\n")
                                        .append("\t\treturn " + fieldName + ";\n")
                                        .append("\t}\n\n");
                            }else{
                                bufferGetSet.append("\tpublic " + fieldType + " get" + getterName + "(){\n")
                                        .append("\t\treturn " + fieldName + ";\n")
                                        .append("\t}\n\n");
                            }
                            //Generate setter
                            bufferGetSet.append("\tpublic void set" + getterName + "(" + fieldType + " " + filedProperty.getName() + "){\n")
                                    .append("\t\tthis." + fieldName + " = " + fieldName + ";\n")
                                    .append("\t}\n\n");
                        }
    
                        if(genToString){//生成toString方法
                            bufferToString.append("\t\t\t\t\"").append(fieldName).append("=\" + ")
                                    .append(fieldName);
                            if(index < size-1){
                                bufferToString.append(" + \",\" + \n");
                            }else{
                                bufferToString.append(" + \"}\";\n");
                            }
                        }
                    }
    
                    index++;
                }
    
                if(parseConfig.isSerializable()){//导入Serializable
                    buffer.append("import java.io.Serializable;\n");
                }
    
                if(importList){//导入List
                    buffer.append("import java.util.List;\n");
                }
    
                if(importBigDecimal){//导入Set
                    buffer.append("import java.math.BigDecimal;\n");
                }
    
                if(importMap){//导入Map
                    buffer.append("import java.util.Map;\n");
                }
    
                if(useLombok){//导入Lombok
                    buffer.append("import lombok.Data;\n");
                }
                buffer.append("\n");
    
                //是否显示头部注释说明
                if(parseConfig.isShowHeader()){
                    String header = parseConfig.getHeader();
                    if(header!=null && header.length()>0){
                        buffer.append("/**\n");
                        buffer.append(" * ")
                                .append(header.replace("\n","\n * "));
                        buffer.append("\n */\n");
                    }
                }
    
                if(useLombok){//添加Lombok的data注解
                    buffer.append("@Data\n");
                }
    
                //拼接类
                buffer.append("public class " + className);
                if(genericity){
                    buffer.append("<T>");
                }
    
                //序列化
                if(parseConfig.isSerializable()){
                    buffer.append(" implements Serializable");
                }
    
                buffer.append(" {\n\n");
    
                //添加字段
                buffer.append(bufferField).append("\n");
    
                if(!useLombok){
    
                    if(genGetterAndSetter){
                        buffer.append(bufferGetSet);
                    }
    
                    if(genToString){
                        //toString结尾
                        bufferToString.append("\t}\n\n");
                        buffer.append(bufferToString);
                    }
                }
    
            }
    
            buffer.append("\n}\n\n");
    
            File dirFile = new File(outPath);
            if(dirFile!=null && !dirFile.exists()){
                dirFile.mkdirs();
            }
    
            //将内容写入到文件
            File file = new File(outPath,javaName);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),parseConfig.getCharsetName()));
            //doc格式的文档解析后会有\u0007字符需统一过滤
            writer.write(isDoc ? buffer.toString().replace("\u0007","") : buffer.toString());
            writer.flush();
            writer.close();
    
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185

    代码 在注解、类型和初值方面 仍然需要优化。

  • 相关阅读:
    如何部署SpringBoot工程
    机器学习简介
    【计算机网络】成功解决 ARP项添加失败:请求的操作需要提升
    C++面向对象:重写、重载、隐藏
    git clone开启云上AI开发
    文件的常用操作(读取压缩文件、解压、删除)
    UI遍历的初步尝试
    操作系统复习:内存管理
    Web安全研究(五)
    【Bug】Access to the path ‘xxx‘ is denied.
  • 原文地址:https://blog.csdn.net/yooppa/article/details/125391585