Excel--03--读Excel生成java代码

Posted 高高for 循环

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Excel--03--读Excel生成java代码相关的知识,希望对你有一定的参考价值。

需求:

读此表生成相对应的java代码

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

前端

先省略…

后端编码

public static void main(String[] args) throws Exception {

        //目标表格
        File file = new File("POI\\\\测试.xlsx");
        //生成文件的路径
        String pathDir ="poi\\\\Util.java";


        if(file.exists() && (file.getName().endsWith("xlx")||file.getName().endsWith("xlsx")||file.getName().endsWith("et"))){

            Map<String, List> map = readXls(file);

            writeJava(map,pathDir);

        }

    }

读取Excel文件

Workbook workbook= WorkbookFactory.create(inputStream)


   //读取Excel文件
    public static Map<String,List> readXls (File file) throws Exception{


        Map<String,List> map = new HashMap<>();

        String fileName=file.getName();

        FileInputStream inputStream = new FileInputStream(file);

        Workbook workbook=null;

        if(fileName.endsWith(".xlsx")){
            workbook=new XSSFWorkbook(inputStream);
        }else {
            workbook=new HSSFWorkbook(inputStream);
        }

    //    Workbook workbook= WorkbookFactory.create(inputStream)

        //默认只读表1
        Sheet sheetAt = workbook.getSheetAt(0);
        if(sheetAt == null){
            return map;
        }

        Row rowTitle = sheetAt.getRow(0);
        int countnull =0;

        int firRow=0;
        int laRow=0;

        //获取合并单元格数目
        int sheetmergeCount = sheetAt.getNumMergedRegions();

        for (int i = 0; i < sheetmergeCount; i++) {
            CellRangeAddress range = sheetAt.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow= range.getLastRow();

            if(lastRow <= laRow){
                continue;
            }else {
                //读取此单元格内容,并封装进list
                List list = addList(firstRow, lastRow, sheetAt);
                //获取方法的名字
                String methodName = sheetAt.getRow(firstRow).getCell(1).toString();

                //把这个list数据封装到map里面 ,key是方法的名字,value是list
                if(methodName !=null && !"".equals(methodName) ){
                    map.put(methodName,list);
                }

                if(laRow<=lastRow){
                    firRow=firstRow;
                    laRow=lastRow;
                }
            }

        }
           return map ;
    }

把excel需要的内容输入list

//把excel需要的内容输入list
    public  static List addList(int firstRow, int lastRow, Sheet sheetAt){

        List<String[]> list=new ArrayList<>();

        //读取此单元格的每一行
        for (int rowNum=firstRow ; rowNum<= lastRow; rowNum++){
            Row row = sheetAt.getRow(rowNum);
            if(row ==null){
                continue;
            }


            String[] strArray= new String[10];

            for (int celIX =0 ;celIX<=6; celIX++){

                Cell cell = row.getCell(celIX);

                strArray[celIX]= cell==null ? "" :cell.toString();
            }

            list.add(strArray);

        }

       return  list;
    }


根据读取的Excel信息,写入java文件

  //根据读取的Excel信息写入java
    public static void writeJava(Map map,String targetPath) throws IOException {

        File tarFile = new File(targetPath);
        if(tarFile.exists()){
            tarFile.delete();
        }else {
            tarFile.createNewFile();
        }


        //读取注释模板文件
        // String fileDemoPath= System.getProperty("user.dir")+File.separator+"lib"+File.separator+"Util.txt";
        String fileDemoPath="D:\\\\JavaDevelop\\\\idea_workplace\\\\iodemo\\\\demo.txt";
        String encoding="UTF-8";

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileDemoPath), encoding));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tarFile), encoding));

        String data;
        //拼接类的开头
        while ((data=bufferedReader.readLine())!=null){
            bufferedWriter.write(data);
            bufferedWriter.newLine();
        }

        bufferedWriter.newLine();
        bufferedWriter.newLine();



        Set<String> set = map.keySet();

       //遍历map

        for(String strkey: set){
            String methodName =strkey;

            List<String[]> list =(List)map.get(strkey);

            //写入拼接方法
            writeMethod(methodName,list,bufferedWriter);
            bufferedWriter.newLine();
            bufferedWriter.newLine();
            bufferedWriter.newLine();

        }

        String lastStr="}";
        bufferedWriter.newLine();
        bufferedWriter.write(lastStr);

        bufferedReader.close();
        bufferedWriter.close();
    }

其中模板方法demo.txt ,可以读取 也可以手动拼接

在这里插入图片描述

系统读取的话

System.getProperty(“user.dir”)+File.separator+“lib”+File.separator+“demo.txt”;

写 拼接方法

 //写入拼接方法
    private static Boolean writeMethod(String name, List<String[]> list, BufferedWriter bufferedWriter) throws IOException {
        //生成方法中map的名字
        String mapName =name;
        //方法名
        String methodName ="";

        //方法名首字母大写

        if(mapName !=null && !"".equals(mapName)){
            methodName=mapName.substring(0,1).toUpperCase()+mapName.substring(1);
        }

        if(list.isEmpty()){
            return  false;
        }

        String colum1=list.get(0)[0].toString();
        String colum2=list.get(0)[1].toString();
        String colum3;
        String colum4;
        String colum5;
        String colum6;

        //获取方法的参数 是必输的 为形参
        StringBuilder strArgs = new StringBuilder();
        StringBuilder strArgs2 = new StringBuilder();

        for(String[] strArr:list){
            colum3 =strArr[2].toString();
            colum4 =strArr[3].toString();
            colum5 =strArr[4].toString();
            colum6 =strArr[5].toString();

            if(colum3.contains("[") || colum3.contains("]") ){
                continue;
            }else if(colum6.contains("必")){
                strArgs.append("String ").append(colum3).append(",");
                strArgs2.append(colum3).append("、");
            }
        }

        //去掉strArgs字符串末尾","
        if (strArgs.length()>0){
            strArgs.deleteCharAt(strArgs.length()-1);
        }


        /**
         * 类型 :  渠道要素信息
         * 通讯区名:
         * <p>
         * 必输字段:
         * 需要其他值获取后自行覆盖值
         * </p>
         * @return 返回封装结果集
         */
        bufferedWriter.write("/**");
        bufferedWriter.newLine();
        bufferedWriter.write("* 类型 :" + colum1);
        bufferedWriter.newLine();
        bufferedWriter.write("* 通讯区名:" + colum2);
        bufferedWriter.newLine();
        bufferedWriter.write("* <p>");
        bufferedWriter.newLine();
        bufferedWriter.write("* 必输字段:" + strArgs2);
        bufferedWriter.newLine();
        bufferedWriter.write("* 需要其他值获取后自行覆盖值");
        bufferedWriter.newLine();
        bufferedWriter.write("* <p>");
        bufferedWriter.newLine();
        bufferedWriter.write("* @return 返回封装结果集");
        bufferedWriter.newLine();
        bufferedWriter.write("*/");
        bufferedWriter.newLine();


        String row1="public static Map<String ,Object> "+"get"+methodName+"("+strArgs +"){" ;
        bufferedWriter.write(row1);
        bufferedWriter.newLine();
        String row2="      Map<String ,Object> "+mapName+" = new HashMap<>();";

        bufferedWriter.newLine();
        bufferedWriter.write(row2);
        bufferedWriter.newLine();
        bufferedWriter.newLine();


        //往map里面添加元素
        for(String[] strArr :list){

            StringBuilder str1 = new StringBuilder();
            StringBuilder str2 = new StringBuilder();

            colum3 =strArr[2].toString();
            colum4 =strArr[3].toString();
            colum5 =strArr[4].toString();
            colum6 =strArr[5].toString();

            if(colum3.contains("[") || colum3.contains("]") ){
                continue;
            }else if(colum6.contains("必")){
                str1.append("       //").append(colum5).append(" ").append(colum6);
                str2.append("       ").append(mapName).append(".put(\\"").append(colum3).append("\\",").append(colum3).append(");");

                bufferedWriter.write(str1.toString());
                bufferedWriter.newLine();
                bufferedWriter.write(str2.toString());
                bufferedWriter.newLine();
                bufferedWriter.newLine();


            }else {
                str1.append("       //").append(colum5).append(" ").append(colum6);
                str2.append("       ").append(mapName).append(".put(\\"").append(colum3).append("\\",").append(" \\"\\");");

                bufferedWriter.write(str1.toString());
                bufferedWriter.newLine();
                bufferedWriter.write(str2.toString());
                bufferedWriter.newLine();
                bufferedWriter.newLine();
            
        }

        String strReturn ="       return "+mapName+" ;";
        String lasrStr="}";

        bufferedWriter.write(strReturn);
        bufferedWriter.newLine();
        bufferedWriter.write(lasrStr);
        
        return true;
        }

以上是关于Excel--03--读Excel生成java代码的主要内容,如果未能解决你的问题,请参考以下文章

java jxls操作excel,怎么把富文本框的内容转换成excel格式的内容

Rails 4数据表导出到excel文件正在工作,但文件不可读

Python与Excel--03Excel模块

JAVA POI 应用系列--生成Excel

在java开发中怎么把word文档读到页面文本框中

[从产品角度学EXCEL 03]-单元格的秘密