此为实物界面图

三个功能:

1.加载rule

2.根据rule,读取excel,处理为同名的16进制文件,类型在rule里写

3.根据rule,读取16进制文件,处理为excel,方便编辑

package code;

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import code.dao.FileByte;

public class Main {
    
    public static void main(String[] args) {
        
        Window LD=new Window();
    }
    
}
main主类
package code;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

import code.dao.BTLDAO;

//初始化
    public class Window {
        JFrame window;
        //规则框
        JTextField ruleText;
        //登录按钮
        JButton loadBtlToExcel;
        JButton loadExcelToBtl;
        JButton loadRule;
        JLabel label;
        ImageIcon background;  
        JPanel imagePanel;  
        Container cp;
        Color color ;
        JFileChooser fileChooser;
        File lastFile;
        File lastRuleFile;
        String currentPath;
        

        String rulePath;
        String btlPath;
        BTLDAO btlFile;
        String fileName;//非前路径和后缀
        Map<String, Object> rsMap = null;
        Toolkit tk = Toolkit.getDefaultToolkit();
      //初始化
        public Window(){
            color = new Color(0,0,255);
            
            window=new JFrame("e社16进制解析器");
            window.setLayout(null);
            window.setSize(400, 600);//设置大小
            window.setLocationRelativeTo(null);//设置居中
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置可关闭
            window.setLayout(null);//设置绝对布局(窗口里面的内容不会随着窗口的改变而改变)
            window.setResizable(false);//设置窗口不可拉伸改变大小
            window.setBackground(new Color(255,255,255));
            //设置背景
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
            background = new ImageIcon(tk.getImage(window.getClass().getResource("/"+Config.Imgs.BG_JPG)));//(Config.Imgs.BG_JPG)
            label= new JLabel(background);
            window.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
            label.setBounds(0,75,background.getIconWidth(), background.getIconHeight());//设置背景标签的位置  
            cp=window.getContentPane(); 
            cp.setLayout(null);
            ((JPanel)cp).setOpaque(false);
            
            //设置用户名标签
            JLabel rule_label =new JLabel("当前规则:");
            rule_label.setBounds(25,30,100,50);
            window.add(rule_label);
            
            //设置信息标签
            JLabel info_label =new JLabel(Config.Infos.INFO_AUTHER);
            info_label.setBounds(25,500,200,50);
            window.add(info_label);
            
            //设置版本
            JLabel vs_label =new JLabel("版本:"+Config.Infos.INFO_VERSION);
            vs_label.setBounds(25,515,200,50);
            window.add(vs_label);
            
            //设置用户名文本框
            ruleText=new JTextField();
            ruleText.setBounds(75, 30, 200, 50);
            ruleText.setEnabled(false);
            ruleText.setForeground(new Color(255,0,0));
            ruleText.setFont(new Font("宋体", Font.PLAIN, 30) );
            window.add(ruleText);
            loadRule=new JButton("加载rule");
            loadRule.setBounds(275, 30, 100, 50);
            loadRule.setBackground(color);
            loadRule.setOpaque(false);
            loadRule.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    System.out.print(Config.Infos.INFO_WISH);
                    loadRule();
                }           
            });
            window.add(loadRule);
            //设置按钮
            loadBtlToExcel=new JButton("加载btl生成excel");
            loadBtlToExcel.setBounds(25, 100, 150, 50);
            loadBtlToExcel.setBackground(color);
            loadBtlToExcel.setOpaque(false);
            loadBtlToExcel.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    loadBtlToExcel();
                    System.out.print(Config.Infos.INFO_WISH);
                }           
            });
            window.add(loadBtlToExcel);
            loadExcelToBtl=new JButton("加载excel生成btl");
            loadExcelToBtl.setBounds(225, 100, 150, 50);
            loadExcelToBtl.setBackground(color);
            loadExcelToBtl.setOpaque(false);
            loadExcelToBtl.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    loadExcelToBtl();
                    System.out.print(Config.Infos.INFO_WISH);
                }           
            });
            window.add(loadExcelToBtl);
            window.setVisible(true);//设置面板可见
            
            currentPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
         }
        
        
        
        //功能1 读取规则,选择规则
        public  void loadRule() {
            rulePath=getPath("xml");
            //System.out.println(rulePath);
            if(rulePath!=null) {
                ruleText.setText(lastRuleFile.getName());
            }
        }
        //功能2 加载btl生成excel
        public void loadBtlToExcel() {
            if(rulePath==null) {
                JOptionPane.showMessageDialog(null, "规则未加载", "fail", JOptionPane.ERROR_MESSAGE);
                return;
            }
            btlPath=getPath(null);
            if(btlPath==null) {
                JOptionPane.showMessageDialog(null, "btl未加载", "fail", JOptionPane.ERROR_MESSAGE);
                return;
            }
            File tempFile =new File(btlPath);  
            
            
            String suffix = btlPath.substring(btlPath.lastIndexOf(".") + 1);
            try {
                btlFile = BTLTooL.LoadBtl(rulePath, btlPath);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "btl加载出错", e.getMessage().toString(), JOptionPane.ERROR_MESSAGE);
                return;
            }
            try {
                rsMap = BTLTooL.getBtlMap(rulePath, btlFile);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "btl信息转换出错", e.getMessage().toString(), JOptionPane.ERROR_MESSAGE);
                return;
            }
            String excelPath = null;
            try {
                excelPath = tempFile.getCanonicalPath();
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, "获取excel导出目录出错", e.getMessage().toString(), JOptionPane.ERROR_MESSAGE);
                return;
            }
            boolean writeExcel = BTLTooL.writeBTLExcel( excelPath.substring(0, excelPath.length()-1-tempFile.getName().length()), tempFile.getName().substring(0, tempFile.getName().lastIndexOf(".")), rulePath, rsMap);
           if(writeExcel) {
               JOptionPane.showMessageDialog(null, "excel导出成功", "ok", JOptionPane.DEFAULT_OPTION);
           }else {
               JOptionPane.showMessageDialog(null, "excel生成出错", "fail", JOptionPane.ERROR_MESSAGE);
               return;
           }
            
        }
        //功能3 加载excel生成btl
        public void loadExcelToBtl() {
            //请先加载规则
            if(rulePath==null) {
                JOptionPane.showMessageDialog(null, "规则未加载", "fail", JOptionPane.ERROR_MESSAGE);
                return;
            }
            String excelPath=getPath("xls");

            if(excelPath==null) {
                JOptionPane.showMessageDialog(null, "excel未加载", "fail", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            File file = new File(excelPath);
            String outDir;
            try {
                outDir=file.getCanonicalPath();
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, "获取导出文件名出错", e.getMessage().toString(), JOptionPane.ERROR_MESSAGE);
                return;
            }
            outDir=excelPath.substring(0, excelPath.length()-1-file.getName().length());
            String fileNamePrefix=excelPath.substring(outDir.length(),excelPath.lastIndexOf(".")+1 );
            String fileNameSuffix = null;
            try {
             fileNameSuffix=ComUtil.getRootElementForMap(rulePath).get("fileType").toString();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "从规则获取文件转换后缀出错", e.getMessage().toString(), JOptionPane.ERROR_MESSAGE);
                return;
            }
            Map btlExcelMap=null;
            try {
                btlExcelMap = BTLTooL.getExcelDataForMap(file);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "读取excel数据出错", e.getMessage().toString(), JOptionPane.ERROR_MESSAGE);
                return;
            }
            try {
            BTLTooL.saveMapBin(rulePath, btlExcelMap, outDir+fileNamePrefix+fileNameSuffix);
            JOptionPane.showMessageDialog(null, "文件转化成功", "ok", JOptionPane.DEFAULT_OPTION);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "转换数据出错", e.getMessage().toString(), JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        
        
        

        public  String getPath(String type) {//jpg,xml
            String path = null;
            fileChooser = new JFileChooser(currentPath);
            FileSystemView fsv = FileSystemView.getFileSystemView(); //注意了,这里重要的一句
            if(type!=null&&type.equals("xml")&&lastRuleFile!=null) {
                fileChooser.setCurrentDirectory(lastRuleFile);
            }else if(lastFile!=null) {
                fileChooser.setCurrentDirectory(lastFile);
            }else if(ComUtil.isEmpty(currentPath)) {
                fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
            }
            fileChooser.setDialogTitle("请选择要加载的文件...");
            fileChooser.setApproveButtonText("确定");
            //fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);//单选,多选
            if(!ComUtil.isEmpty(type)) {
                fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());//去掉全部选项
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("仅能打开"+type+"格式文件", type));
            }
            int returnVal = fileChooser.showOpenDialog(fileChooser);
            
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                path = fileChooser.getSelectedFile().getAbsolutePath();//这个就是你选择的文件夹的路径
                //System.out.println(path);
                if(type!=null&&type.equals("xml")) {
                    lastRuleFile=fileChooser.getSelectedFile();
                }else {
                    lastFile=fileChooser.getSelectedFile();
                }
                return path;
            }
            return null;
        }
        
    }
Window窗口类
package code;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class ComUtil {
    //加载xml
    // 此方法调用dom4j来解析xml
    public static JSONObject XmlRead(String path) {
        // 解析books.xml文件
        // 创建SAXReader的对象reader
        SAXReader reader = new SAXReader();
        JSONObject jsonObject = new JSONObject();
        try {
            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
            Document document = reader.read(new File(path));
            // 通过document对象获取根节点bookstore
            Element bookStore = document.getRootElement();
            // 通过element对象的elementIterator方法获取迭代器
            Iterator it = bookStore.elementIterator();
            // 遍历迭代器,获取根节点中的信息()
            JSONArray jsonArray = new JSONArray();
            
            while (it.hasNext()) {
                
                // System.out.println("=====开始遍历xml属性=====");
                Element book = (Element) it.next();
                Map<String, Object> param = new HashMap<String, Object>();
                JSONArray nodeList = new JSONArray();
                
                // 获取book的属性名以及 属性值
                List<Attribute> bookAttrs = book.attributes();
                for (Attribute attr : bookAttrs) {
                    //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue());
                    param.put(attr.getName(), attr.getValue());
                }
                
                jsonObject.put("attribute", jsonArray);
                // 解析子节点的信息
                Iterator itt = book.elementIterator();
                while (itt.hasNext()) {
                    Element bookChild = (Element) itt.next();
                    List<Attribute> bookAttrss = bookChild.attributes();
                    
                    JSONObject obj = new JSONObject();
                    
                    for (Attribute attr : bookAttrss) {
                        //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue());
                        obj.put(attr.getName(), attr.getValue());
                    }
                    
                    nodeList.add(obj);
                    // System.out.println("节点名:" + bookChild.getName() +
                    // "--节点值:" + bookChild.getStringValue());
                    
                }
                param.put("nodeList", nodeList);
                jsonArray.add(param);
                
                // System.out.println("=====结束遍历xml属性=====");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    
    
    public  static Map getRootElementForMap(String path){
     // 解析books.xml文件
        // 创建SAXReader的对象reader
        SAXReader reader = new SAXReader();
        JSONObject jsonObject = new JSONObject();
        Element root = null ;
        Map<String, Object> param = new HashMap<String, Object>();
        try {
            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
            Document document = reader.read(new File(path));
            // 通过document对象获取根节点bookstore
             root = document.getRootElement();
             JSONArray nodeList = new JSONArray();
             
             // 获取book的属性名以及 属性值
             List<Attribute> rootAttrs = root.attributes();
             for (Attribute attr : rootAttrs) {
                 //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue());
                 param.put(attr.getName(), attr.getValue());
             }
           
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return param;
    }
    
    //读取16进制文件 yjl
    public static byte[] readFile(String file) throws IOException {
        InputStream is = new FileInputStream(file);
        int length = is.available();
        byte bt[] = new byte[length];
        is.read(bt);
        return bt;
    }
    
    //Integer.parseInt(buf.substring(bufTag, bufTag + cutL), 16)+"";
    public static String converLong(String param) {
        int len = param.length();
        if (len != 8) {
            return "长度不符";
        } else {
            String str1 = param.substring(0, 2);
            String str2 = param.substring(2, 4);
            String str3 = param.substring(4, 6);
            String str4 = param.substring(6, 8);
            return String.valueOf(Integer.parseInt(str4 + str3 + str2 + str1, 16));
        }
        
    }
    
    public static String converInteger(String param) {
        int len = param.length();
        if (len != 4) {
            return "长度不符";
        } else {
            String str1 = param.substring(0, 2);
            String str2 = param.substring(2, 4);
            String str3 = String.valueOf(Integer.parseInt(str2 + str1, 16));
            return str3;
        }
    }
    
    public static String converSingle(String param) {
        int len = param.length();
        if (len != 8) {
            return "长度不符";
        } else {//3100cdcd
            String str1 = param.substring(0, 2);
            String str2 = param.substring(2, 4);
            String str3 = param.substring(4, 6);
            String str4 = param.substring(6, 8);
            return String.valueOf(Float.intBitsToFloat(Integer.valueOf(str4 + str3 + str2 + str1, 16)));
            //Float f=0.15490197f;  反向
            //System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
        }
    }
    
    public static String converByte(String param) {
        int len = param.length();
        if (len != 2) {
            return "长度不符";
        } else {
            String str1 = param.substring(0, 2);
            return String.valueOf(Integer.parseInt(str1, 16));
        }
    }
    
    public static String converString(String param) {
        int len = param.length();
        if (len != 32) {
            return "长度不符";
        } else {//64 65 31 00 CD CD CD CD CD CD CD CD CD CD CD CD;
            int i = getCharacterPosition(param, "cd", 1);
            if (i != -1) {
                param = param.substring(0, i);
                System.out.println(param);
                param = convertHexToString(param);
            } else {
                param = "解析错误";
            }
            return param;
        }
    }
    
    public static String transLong(String param) {
        param = Integer.toHexString(Integer.parseInt(param)) + "";
        int size = 8;
        if (param.length() != size) {
            param = formmatString(param, size, 1, "0");
        }
        String str1 = param.substring(0, 2);
        String str2 = param.substring(2, 4);
        String str3 = param.substring(4, 6);
        String str4 = param.substring(6, 8);
        return String.valueOf(str4 + str3 + str2 + str1);
    }
    
    public static String transInteger(String param) {
        param = Integer.toHexString(Integer.parseInt(param)) + "";
        int size = 4;
        if (param.length() != size) {
            param = formmatString(param, size, 1, "0");
        }
        String str1 = param.substring(0, 2);
        String str2 = param.substring(2, 4);
        return String.valueOf(str2 + str1);
    }
    
    public static String transSingle(String param) {
        param = Integer.toHexString(Float.floatToIntBits(Float.parseFloat(param))) + "";
        int size = 8;
        if (param.length() != size) {
            param = formmatString(param, size, 1, "0");
        }
        String str1 = param.substring(0, 2);
        String str2 = param.substring(2, 4);
        String str3 = param.substring(4, 6);
        String str4 = param.substring(6, 8);
        return String.valueOf(str4 + str3 + str2 + str1);
        //Float f=0.15490197f;  反向
        //System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
    }
    
    public static String transByte(String param) {
        param = Integer.toHexString(Integer.parseInt(param)) + "";
        int size = 2;
        if (param.length() != size) {
            param = formmatString(param, size, 1, "0");
            
        }
        return String.valueOf(param);
    }
    
    public static String transString(String param) {
        param = convertStringToHex(param);
        int size = 32;
        if (param.length() != size) {
            //补位cd
            int i = (32 - param.length()) / 2;
            for (int j = 0; j < i; j++) {
                param = param + "cd";
            }
        }
        return param;
    }
    
    public static String convertStringToHex(String str) {
        
        char[] chars = str.toCharArray();
        
        StringBuffer hex = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            hex.append(Integer.toHexString((int) chars[i]));
        }
        
        return hex.toString();
    }
    
    public static String convertHexToString(String hex) {
        
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            
            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
            
            temp.append(decimal);
        }
        
        return sb.toString();
    }
    
    public static int getCharacterPosition(String url, String s, int i) {
        //这里是获取"/"符号的位置 lastindexof从字符串末尾开始检索,检索到子字符
        Matcher slashMatcher = Pattern.compile(s).matcher(url);
        int mIdx = 0;
        while (slashMatcher.find()) {
            mIdx++;
            //当"/"符号第i次出现的位置
            if (mIdx == i) {
                break;
            }
        }
        int rs;
        try {
            rs = slashMatcher.start();
        } catch (Exception e) {
            rs = -1;
        }
        return rs;
    }
    
    //对象转Map
    public static Map JBeanToMap(Object obj) {
        Map<String, Object> reMap = new HashMap<String, Object>();
        if (obj == null)
            return null;
        Field[] fields = obj.getClass().getDeclaredFields();
        try {
            for (int i = 0; i < fields.length; i++) {
                try {
                    Field f = obj.getClass().getDeclaredField(fields[i].getName());
                    f.setAccessible(true);
                    Object o = f.get(obj);
                    reMap.put(fields[i].getName(), o);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return reMap;
    }
    
    //示例 setVal(obj,"setUpdateUser","修改人"); 给对象赋值
    public static void setVal(Object obj, String methodName, Object value) {
        if (value == null || obj == null) {
            return;
        }
        String method_name = methodName;
        Method[] methods = obj.getClass().getMethods();
        for (Method method : methods) {
            /**
             * 因为这里只是调用bean中属性的set方法,属性名称不能重复 所以set方法也不会重复,所以就直接用方法名称去锁定一个方法
             * (注:在java中,锁定一个方法的条件是方法名及参数)
             **/
            if (method.getName().equals(method_name)) {
                Class[] parameterC = method.getParameterTypes();
                try {
                    /**
                     * 如果是基本数据类型时(如int、float、double、byte、char、boolean)
                     * 需要先将Object转换成相应的封装类之后再转换成对应的基本数据类型 否则会报
                     * ClassCastException
                     **/
                    if (parameterC[0] == int.class) {
                        method.invoke(obj, ((Integer) value).intValue());
                        break;
                    } else if (parameterC[0] == float.class) {
                        method.invoke(obj, ((Float) value).floatValue());
                        break;
                    } else if (parameterC[0] == double.class) {
                        method.invoke(obj, ((Double) value).doubleValue());
                        break;
                    } else if (parameterC[0] == byte.class) {
                        method.invoke(obj, ((Byte) value).byteValue());
                        break;
                    } else if (parameterC[0] == char.class) {
                        method.invoke(obj, ((Character) value).charValue());
                        break;
                    } else if (parameterC[0] == boolean.class) {
                        method.invoke(obj, ((Boolean) value).booleanValue());
                        break;
                    } else {
                        method.invoke(obj, parameterC[0].cast(value));
                        break;
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //map转对象
    public static Object mapToJBean(Class<?> clazz, Map<String, Object> map) throws Exception {
        Object javabean = clazz.newInstance(); // 构建对象
        Method[] methods = clazz.getMethods(); // 获取所有方法
        for (Method method : methods) {
            if (method.getName().startsWith("set")) {
                String field = method.getName(); // 截取属性名
                field = field.substring(field.indexOf("set") + 3);
                field = field.toLowerCase().charAt(0) + field.substring(1);
                if (map.containsKey(field)) {
                    method.invoke(javabean, map.get(field));
                }
            }
        }
        return javabean;
    }
    
    //将第一个字母大写
    public static String UpperInitial(String str) {
        if (str != null && str != "") {
            str = str.substring(0, 1).toUpperCase() + str.substring(1);
        }
        return str;
    }
    
    //List 集合去除null元素
    public static <T> List<T> removeNull(List<? extends T> oldList) {
        // 你没有看错,真的是有 1 行代码就实现了
        oldList.removeAll(Collections.singleton(null));
        return (List<T>) oldList;
    }
    
    //获取单个对象的值
    public static Map<String, Object> getKeyAndValue(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 得到类对象
        Class userCla = (Class) obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            f.setAccessible(true); // 设置些属性是可以访问的
            Object val = new Object();
            try {
                val = f.get(obj);
                // 得到此属性的值
                if (val != null) {
                    map.put(f.getName(), val);// 设置键值
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        //System.out.println("单个对象的所有键值==反射==" + map.toString());
        return map;
    }
    
    /*
     * 处理字符串,进行前后补位 resultString ,表原字符串 length,处理后要求长度 flag,1表示前面增加,0表示后增加
     * str1,要补位的字符串
     */
    public static String formmatString(String resultString, int length, int flag, String str1) {
        for (; resultString.getBytes().length < length;) {
            if (flag == 1) {
                resultString = str1 + resultString;
            } else {
                resultString = resultString + str1;
            }
            
        }
        return resultString;
    }
    
    //使用反射获取list大小
    public static int getArrayListCapacity(ArrayList<?> arrayList) {
        Class<ArrayList> arrayListClass = ArrayList.class;
        try {
            //获取 elementData 字段
            Field field = arrayListClass.getDeclaredField("elementData");
            //开始访问权限
            field.setAccessible(true);
            //把示例传入get,获取实例字段elementData的值
            Object[] objects = (Object[]) field.get(arrayList);
            //返回当前ArrayList实例的容量值
            return objects.length;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    
    public static boolean isEmpty(CharSequence cs) {
        return (cs == null) || (cs.length() == 0);
    }
    
    public static String rightTrim(String str) {
        if (str == null) {
            return "";
        }
        int length = str.length();
        for (int i = length - 1; i >= 0; i--) {
            if (str.charAt(i) != 0x20) {
                break;
            }
            length--;
        }
        return str.substring(0, length);
    }
    
    
}
ComUtil通用工具类
package code;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import code.dao.BTLDAO;
import code.dao.DefRule;
import code.dao.FileByte;
import code.dao.module.BtlModule0;
import code.dao.module.BtlModule1;
import code.dao.module.BtlModule10;
import code.dao.module.BtlModule11;
import code.dao.module.BtlModule12;
import code.dao.module.BtlModule13;
import code.dao.module.BtlModule14;
import code.dao.module.BtlModule15;
import code.dao.module.BtlModule16;
import code.dao.module.BtlModule17;
import code.dao.module.BtlModule18;
import code.dao.module.BtlModule19;
import code.dao.module.BtlModule2;
import code.dao.module.BtlModule20;
import code.dao.module.BtlModule3;
import code.dao.module.BtlModule4;
import code.dao.module.BtlModule5;
import code.dao.module.BtlModule6;
import code.dao.module.BtlModule7;
import code.dao.module.BtlModule8;
import code.dao.module.BtlModule9;

public class BTLTooL {
    //读取通用btl,以及相关处理
    public static void main(String[] args) {
        String rule = Config.Rules.WC4_RULE;
        String btl = Config.Btls.WC4_BTL;
        BTLDAO binFile = null;
        Map<String, Object> rsMap = null;
        /*
        
        try {
            binFile = LoadBtl(rule, btl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            rsMap = getBtlMap(rule, binFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        saveMapBin(rule, rsMap, "D://wc4Test.btl");*/
        
        /*
         String path = "D://ExcelDemo";//存放文件夹位置 boolean writeExcel;
         writeExcel = writeBTLExcel( path, "zwen", rule, rsMap);
         System.out.println(writeExcel); System.out.println("ok");
         */
        
        File file = new File("D:\\ExcelDemo\\zwen.xls");
        Map btlExcelMap=null;
        
        try {
            btlExcelMap = getExcelDataForMap(file);
            binFile=getBtlByExcelMap(rule,btlExcelMap);
            rsMap = getBtlMap(rule, binFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        saveMapBin(rule, btlExcelMap, "D://wc4Test.btl");
        
        
    }
    
    //加载Btl
    public static BTLDAO LoadBtl(String rule, String path) throws Exception {
        byte[] rsbt = null;
        BTLDAO btl = new BTLDAO();
        BtlModule0 bi;
        StringBuilder buf = new StringBuilder();
        String cutStr = "";
        int bufTag = 0;
        int cutSumCt = 1;//总循环次数
        int mapW = 0, mapH = 0, i;
        JSONObject row;
        List<DefRule> rs;
        Map rsMap = null;
        Map biMap = null;
        
        {//读取bin
            try {
                rsbt = ComUtil.readFile(path);//"D:\\test1.bin"
            } catch (IOException e) {
                e.printStackTrace();
            }
            int line = 0;// 十六进制标记
            for (byte d : rsbt) {
                if (line % 1 == 0) {
                    buf.append(String.format("%02x", d));
                    // System.out.println(String.format("%02x", d));
                }
            }
        }
        { //得到基础信息 
            cutStr = "bm0";
            row = getInfoByRootName(rule, cutStr);
            rs = getDefRuleInfosByRow(row);
            bi = new BtlModule0();
            rsMap = cutBtl(rs, bi, buf, bufTag, cutSumCt);
            bi = (BtlModule0) rsMap.get("T");
            btl.setBm0(bi);
            bufTag = Integer.parseInt(rsMap.get("bufTag").toString());
            biMap = ComUtil.JBeanToMap(bi);
            for (i = 0; i < rs.size(); i++) {
                if (rs.get(i).getFunction().toString().equals("mapH")) {
                    mapH = Integer.parseInt(biMap.get(rs.get(i).getId()).toString());
                }
                if (rs.get(i).getFunction().toString().equals("mapW")) {
                    mapW = Integer.parseInt(biMap.get(rs.get(i).getId()).toString());
                }
            }
            if (mapW * mapH == 0) {
                throw new Exception("没有得到有效的宽高");
            }
        }
        { //重复读取所有基本信息
            Object[] objects = new Object[] { (new BtlModule1()), (new BtlModule2()), (new BtlModule3()), (new BtlModule4()), (new BtlModule5()), (new BtlModule6()), (new BtlModule7()), (new BtlModule8()), (new BtlModule9()), (new BtlModule10()), (new BtlModule11()), (new BtlModule12()), (new BtlModule13()), (new BtlModule14()), (new BtlModule15()), (new BtlModule16()), (new BtlModule17()),
                    (new BtlModule18()), (new BtlModule19()), (new BtlModule20()) };
            String[] cutStrs = new String[] { "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" };
            for (i = 0; i < objects.length; i++) {
                row = getInfoByRootName(rule, cutStrs[i]);
                if (row != null) {
                    rs = getDefRuleInfosByRow(row);
                    if (row.getBoolean("ifCycle")) {
                        if (row.getString("Count").equals("one")) {
                            cutSumCt = 1;
                        } else if (row.getString("Count").equals("sumGride")) {
                            cutSumCt = mapW * mapH;
                        } else {
                            if (biMap.get(row.getString("Count")) != null) {
                                cutSumCt = Integer.parseInt((String) biMap.get(row.getString("Count")));
                            } else {
                                cutSumCt = 0;
                            }
                        }
                    } else {
                        cutSumCt = 1;
                    }
                    rsMap = cutBtl(rs, objects[i], buf, bufTag, cutSumCt);
                    ComUtil.setVal(btl, "set" + ComUtil.UpperInitial(cutStrs[i]), rsMap.get("T"));
                    bufTag = Integer.parseInt(rsMap.get("bufTag").toString());
                }
            }
        }
        return btl;
    }
    
    //从主节点获取信息
    public static JSONObject getInfoByRootName(String path, String rootName) {
        List<DefRule> defRules = new ArrayList<DefRule>();
        DefRule defRule;
        JSONObject obj = ComUtil.XmlRead(path);
        JSONArray array = obj.getJSONArray("attribute");
        JSONObject row = null;
        for (int i = 0; i < array.size(); i++) {
            row = array.getJSONObject(i);
            if (row.get("id").equals(rootName)) {
                return row;
            }
        }
        return null;
    }
    
    public  static String getFileTypeByRule(String path){
        JSONObject obj = ComUtil.XmlRead(path);
        JSONArray array = obj.getJSONArray("attribute");
        JSONObject row = null;
        for (int i = 0; i < array.size(); i++) {
            row = array.getJSONObject(i);
            if (row.get("fileType")!=null) {
                return row.get("fileType").toString();
            }
        }
        return null;
    }
    
    
    //根据pathName 来获取  List<DefRule> rootName为分节点的id
    public static List<DefRule> getDefRuleInfosByRow(JSONObject row) {
        List<DefRule> defRules = new ArrayList<DefRule>();
        DefRule defRule;
        JSONObject row2 = null;
        JSONArray arraycoord = row.getJSONArray("nodeList");
        for (int j = 0; j < arraycoord.size(); j++) {
            row2 = arraycoord.getJSONObject(j);
            defRule = new DefRule();
            defRule.setName(row2.getString("name"));
            defRule.setSize(row2.getIntValue("size"));
            defRule.setType(row2.getString("type"));
            defRule.setRemark(row2.getString("remark"));
            defRule.setFunction(row2.getString("function"));
            defRule.setDefaul(row2.getString("defaul"));
            defRule.setId(row2.getString("id"));
            defRules.add(defRule);
        }
        return defRules;
    }
    
    //切割btl根据xml的记录
    private static <T> Map<String, Object> cutBtl(List<DefRule> rs, T item, StringBuilder buf, int bufTag, int cycleCount) {
        Map<String, Object> rsMap = new HashMap<String, Object>();
        List<T> ts = new ArrayList<T>();
        Class clazz = item.getClass();
        Field[] fieldName;
        Class clazs;
        Field f = null;
        int beginBufTag = bufTag;
        int cutL, c;
        String str = null;
        
        for (c = 0; c < cycleCount; c++) {
            fieldName = clazz.getDeclaredFields();
            try {
                item = (T) clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            clazs = item.getClass();
            for (DefRule r : rs) {
                for (int i = 0; i < fieldName.length; i++) {
                    // 创建实例
                    try {
                        f = clazs.getDeclaredField(fieldName[i].getName());
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    }
                    f.setAccessible(true);
                    if (r.getId().equals(fieldName[i].getName().toString())) {
                        cutL = r.getSize();
                        //System.out.println("B:Name1:"+fieldName[i].getName()+" c:"+c+" bs:"+bufTag+"~"+(bufTag + cutL)+" v:"+buf.substring(bufTag, bufTag + cutL));
                        if (r.getType().equals("Byte")) {
                            str = ComUtil.converByte(buf.substring(bufTag, bufTag + cutL));
                        } else if (r.getType().equals("Integer")) {
                            str = ComUtil.converInteger(buf.substring(bufTag, bufTag + cutL));
                        } else if (r.getType().equals("Long")) {
                            str = ComUtil.converLong(buf.substring(bufTag, bufTag + cutL));
                        } else if (r.getType().equals("Single")) {
                            str = ComUtil.converSingle(buf.substring(bufTag, bufTag + cutL));
                        } else if (r.getType().equals("String")) {
                            str = ComUtil.converString(buf.substring(bufTag, bufTag + cutL));
                        } else if (r.getType().equals("?")) {
                            str = buf.substring(bufTag, bufTag + cutL);
                        } else {
                            str = buf.substring(bufTag, bufTag + cutL);
                        }
                        
                        if (c < 1) {
                            System.out.println("id:" + r.getId() + ":" + r.getName() + " c:" + c + " size:" + cutL + " N:" + r.getRemark() + " value:" + str);
                        }
                        bufTag = bufTag + cutL;
                        
                        try {
                            f.set(item, str);
                        } catch (IllegalArgumentException | IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            if (item != null) {
                ts.add(item);
            }
        }
        
        if (cycleCount == 1 && beginBufTag == 0) {
            rsMap.put("T", item);
        } else {
            ComUtil.removeNull(ts);
            rsMap.put("T", ts);
        }
        rsMap.put("bufTag", bufTag);
        return rsMap;
    }
    
    //根据map转为list类 废弃
    private static <T> List<T> getBtlMoudleList(List<DefRule> rs, List list,Object o){
        Map<String, Object> rsMap = new HashMap<String, Object>();
        List<T> ts = new ArrayList<T>();
        T item=(T) o;
        Class clazz = item.getClass();
        Field[] fieldName;
        Class clazs;
        Field f = null;
        int cutL, c;
        String str = null;
        
        for (c = 0; c < list.size(); c++) {
            fieldName = clazz.getDeclaredFields();
            try {
                item = (T) clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            clazs = item.getClass();
            for (DefRule r : rs) {
                for (int i = 0; i < fieldName.length; i++) {
                    // 创建实例
                    try {
                        f = clazs.getDeclaredField(fieldName[i].getName());
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    }
                    f.setAccessible(true);
                    if (r.getId().equals(fieldName[i].getName().toString())) {
                        cutL = r.getSize();
                        //System.out.println("B:Name1:"+fieldName[i].getName()+" c:"+c+" bs:"+bufTag+"~"+(bufTag + cutL)+" v:"+buf.substring(bufTag, bufTag + cutL));
                        str=((Map)list.get(c)).get(fieldName[i].getName().toString()).toString();
                        if (c < 1) {
                            System.out.println("id:" + r.getId() + ":" + r.getName() + " c:" + c + " size:" + cutL + " N:" + r.getRemark() + " value:" + str);
                        }
                        try {
                            f.set(item, str);
                        } catch (IllegalArgumentException | IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            if (item != null) {
                ts.add(item);
            }
        }
        return ts;
    }
    
    //读取btl,转为map
    public static Map getBtlMap(String rule, BTLDAO binFile) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        
        int i;
        Object om;
        Map map = null;
        List<Map<String, Object>> tempMaps;
        Map<String, Object> rsMap = new HashMap();
        Object s;
        JSONObject row;
        
        {//遍历btl
            Field[] fields = binFile.getClass().getDeclaredFields();//Object是已经被赋值的对象实例
            for (Field field : fields) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                //如果是list类
                if (List.class.isAssignableFrom(field.getType())) {
                    Type t = field.getGenericType();
                    if (t instanceof ParameterizedType) {
                        ParameterizedType pt = (ParameterizedType) t;
                        Class clz = (Class) pt.getActualTypeArguments()[0];//得到对象list中实例的类型
                        if (field.get(binFile) != null) {
                            Class clazz = field.get(binFile).getClass();//获取到属性的值的Class对象
                            Method m = clazz.getDeclaredMethod("size");
                            int size = (Integer) m.invoke(field.get(binFile));//调用list的size方法,得到list的长度
                            tempMaps = new ArrayList<Map<String, Object>>();
                            for (int i2 = 0; i2 < size; i2++) {//遍历list,调用get方法,获取list中的对象实例
                                Method getM = clazz.getDeclaredMethod("get", int.class);
                                if (!getM.isAccessible()) {
                                    getM.setAccessible(true);
                                    s = getM.invoke(field.get(binFile), i2);
                                    map = ComUtil.getKeyAndValue(s);
                                    tempMaps.add(map);
                                }
                            }
                            rsMap.put(field.getName(), tempMaps);
                        }
                    }
                } else {//否则为普通类
                    field.setAccessible(true);
                    Object value = field.get(binFile);
                    map = ComUtil.getKeyAndValue(value);
                    rsMap.put(field.getName(), map);
                }
            }
        }
        {//检查类数量
            String[] cutStrs = new String[] { "bm0", "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" };
            for (i = 0; i < cutStrs.length; i++) {
                row = getInfoByRootName(rule, cutStrs[i]);
                if (row != null && row.getBoolean("ifCycle")) {
                    if (!(row.getString("Count").equals("one") && row.getString("Count").equals("sumGride"))) {
                        map.put(row.getString("Count"), ComUtil.getArrayListCapacity((ArrayList<?>) rsMap.get(cutStrs[i])));
                        // System.out.println(row.getString("Count")+":"+":"+ComUtil.getArrayListCapacity((ArrayList<?>) rsMap.get(cutStrs[i])));
                    }
                }
            }
        }
        
        return rsMap;
    }
    
    //根据规则解析map生成bin
    public static void saveMapBin(String rule, Map map, String path) {
        int i, s;
        JSONObject row;
        List<DefRule> rs;
        List<Map> list;
        Map m;
        String temStr = null;
        StringBuilder buf = new StringBuilder();
        FileByte out = new FileByte();
        String[] cutStrs = new String[] { "bm0", "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" };
        
        for (i = 0; i < cutStrs.length; i++) {
            row = getInfoByRootName(rule, cutStrs[i]);
            if (row != null) {
                rs = getDefRuleInfosByRow(row);
                if (row.get("ifCycle").equals("true")) {
                    list = (List<Map>) map.get(cutStrs[i]);
                    for (Map lMap : list) {
                        for (DefRule r : rs) {
                            if (lMap.containsKey(r.getId())) {
                                if (r.getType().equals("Byte")) {
                                    temStr = ComUtil.transByte(lMap.get(r.getId()).toString());
                                } else if (r.getType().equals("Integer")) {
                                    temStr = ComUtil.transInteger(lMap.get(r.getId()).toString());
                                } else if (r.getType().equals("Long")) {
                                    temStr = ComUtil.transLong(lMap.get(r.getId()).toString());
                                } else if (r.getType().equals("Single")) {
                                    temStr = ComUtil.transSingle(lMap.get(r.getId()).toString());
                                } else if (r.getType().equals("String")) {
                                    temStr = ComUtil.transString(lMap.get(r.getId()).toString());
                                } else if (r.getType().equals("?")) {
                                    temStr = lMap.get(r.getId()).toString();
                                } else {
                                    temStr = lMap.get(r.getId()).toString();
                                }
                                buf.append(temStr);
                            }
                        }
                    }
                } else {
                    if(map.get(cutStrs[i])instanceof java.util.List) {
                    m = (Map) ((List)map.get(cutStrs[i])).get(0);
                    }else {
                        m = (Map) map.get(cutStrs[i]); 
                    }
                    
                    
                    for (DefRule r : rs) {
                        if (r.getType().equals("Byte")) {
                            temStr = ComUtil.transByte(m.get(r.getId()).toString());
                        } else if (r.getType().equals("Integer")) {
                            temStr = ComUtil.transInteger(m.get(r.getId()).toString());
                        } else if (r.getType().equals("Long")) {
                            temStr = ComUtil.transLong(m.get(r.getId()).toString());
                        } else if (r.getType().equals("Single")) {
                            temStr = ComUtil.transSingle(m.get(r.getId()).toString());
                        } else if (r.getType().equals("String")) {
                            temStr = ComUtil.transString(m.get(r.getId()).toString());
                        } else if (r.getType().equals("?")) {
                            temStr = m.get(r.getId()).toString();
                        } else {
                            temStr = m.get(r.getId()).toString();
                        }
                        buf.append(temStr);
                    }
                }
            }
        }
        
        {
            for (s = 0; s < (int) (buf.length() / 2); s++) {
                try {
                    out.writeByte(Integer.parseInt(buf.substring(s * 2, (s + 1) * 2), 16));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileOutputStream fs;
            try {
                fs = new FileOutputStream(path);
                fs.write(out.getByte());
                fs.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    
  
    
    //rule 规则
    //map 类
    //folder 文件夹
    //fileName  
    public static boolean writeBTLExcel(String folder, String fileName, String rule, Map map) {
        if (ComUtil.isEmpty(folder) || ComUtil.isEmpty(fileName)) {
            return false;
        }
        // 判断路径是否正确
        File file = new File(folder);
        if (!file.isDirectory()) {
            return false;
        }
        // 设置文件后缀
        if (!fileName.endsWith(".xls")) {
            fileName = fileName + ".xls";
        }
        
        String[] cutStrs = new String[] { "bm0", "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" };
        JSONObject jsonRow;
        List<DefRule> rs;
        List<Map> list;
        Map m;
        HSSFSheet sheet;
        HSSFRow row, row1;
        List<String> data;
        HSSFPatriarch p;
        HSSFComment comment;
        // 第一步,创建一个workbook对应一个excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        //1加载规则,开始循环
        for (int w = 0; w < cutStrs.length; w++) {
            jsonRow = getInfoByRootName(rule, cutStrs[w]);
            if (jsonRow != null) {
                rs = getDefRuleInfosByRow(jsonRow);
                if (jsonRow.get("ifCycle").equals("true")) {
                    list = (List<Map>) map.get(cutStrs[w]);
                    // 第二步,在workbook中创建一个sheet对应excel中的sheet
                    sheet = workbook.createSheet(cutStrs[w]);
                    //绘制批注
                    p=sheet.createDrawingPatriarch();
                    // 第三步,在sheet表中添加表头第0行,老版本的poi对sheet的行列有限制
                    row = sheet.createRow(0);
                    // 第四步,创建单元格,设置表头
                    for (int i = 0; i < rs.size(); i++) {
                        //添加备注
                        if(!rs.get(i).getRemark().equals("?")) {
                            comment=p.createComment(new HSSFClientAnchor(0,0,0,0,(short)3,3,(short)5,6));
                            //输入批注信息
                            comment.setString(new HSSFRichTextString(rs.get(i).getRemark())); 
                            row.createCell(i).setCellComment(comment);
                        }
                        row.createCell(i).setCellValue(rs.get(i).getId());
                    }
                    // 第五步,写入实体数据,实际应用中这些数据从数据库得到,对象封装数据,集合包对象。对象的属性值对应表的每行的值
                    for (int i = 0; i < list.size(); i++) {
                        row1 = sheet.createRow(i + 1);
                        // 创建单元格设值
                        for (int j = 0; j < rs.size(); j++) {
                            if (list.get(i).containsKey(rs.get(j).getId())) {
                                row1.createCell(j).setCellValue(list.get(i).get(rs.get(j).getId()).toString());
                            }
                        }
                    }
                } else {
                    if (map.containsKey(cutStrs[w])) {
                        m = (Map) map.get(cutStrs[w]);
                        // 第二步,在workbook中创建一个sheet对应excel中的sheet
                        sheet = workbook.createSheet(cutStrs[w]);
                      //绘制批注
                        p=sheet.createDrawingPatriarch();
                        // 第三步,在sheet表中添加表头第0行,老版本的poi对sheet的行列有限制
                        row = sheet.createRow(0);
                        row1 = sheet.createRow(1);
                        // 第四步,创建单元格,设置表头
                        for (int i = 0; i < rs.size(); i++) {
                            
                          //添加备注
                            if(!rs.get(i).getRemark().equals("?")) {
                                comment=p.createComment(new HSSFClientAnchor(0,0,0,0,(short)3,3,(short)5,6));
                                //输入批注信息
                                comment.setString(new HSSFRichTextString(rs.get(i).getRemark())); 
                                row.createCell(i).setCellComment(comment);
                            }
                            row.createCell(i).setCellValue(rs.get(i).getId());
                            row1.createCell(i).setCellValue(m.get(rs.get(i).getId()).toString());
                        }
                    }
                }
            }
            
        }
        // 将文件保存到指定的位置
        try {
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(folder + "\\" + fileName);
            workbook.write(fos);
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    
    //格式表头必须占一行!
    public static Map getExcelDataForMap(File file)throws FileNotFoundException, IOException {

        int rowSize = 0;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        Map<String, Object> rsMap = new HashMap();
        Map tempMap = null;
        List<Map<String, Object>> tempMaps = null;
        
        POIFSFileSystem fs = new POIFSFileSystem(in);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFCell cell = null;HSSFCell headCell = null;
        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            
            HSSFSheet st = wb.getSheetAt(sheetIndex);
            // 第一行为标题,不取
            tempMaps = new ArrayList<Map<String, Object>>();
            for (int rowIndex = 1; rowIndex <= st.getLastRowNum(); rowIndex++) {
                HSSFRow headR = st.getRow(0);
                HSSFRow row = st.getRow(rowIndex);
               if (row == null) {
                   continue;
               }
               int tempRowSize = row.getLastCellNum() + 1;
               if (tempRowSize > rowSize) {
                   rowSize = tempRowSize;

               }
               boolean hasValue = false;
               tempMap = new HashMap();
               for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
                   String value = "";
                   String headV = "";
                   cell = row.getCell(columnIndex);
                   headCell=headR.getCell(columnIndex);
                   if (cell != null) {
                      // 注意:一定要设成这个,否则可能会出现乱码
                      //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                      switch (cell.getCellType()) {
                      case HSSFCell.CELL_TYPE_STRING:
                          value = cell.getStringCellValue();
                          break;
                      case HSSFCell.CELL_TYPE_NUMERIC:
                          if (HSSFDateUtil.isCellDateFormatted(cell)) {
                             Date date = cell.getDateCellValue();
                             if (date != null) {
                                 value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                             } else {
                                 value = "";
                             }
                          } else {
                             value = new DecimalFormat("0").format(cell.getNumericCellValue());
                          }
                          break;
                      case HSSFCell.CELL_TYPE_FORMULA:
                          // 导入时如果为公式生成的数据则无值
                          if (!cell.getStringCellValue().equals("")) {
                             value = cell.getStringCellValue();
                          } else {
                             value = cell.getNumericCellValue() + "";
                          }
                          break;

                      case HSSFCell.CELL_TYPE_BLANK:
                          break;

                      case HSSFCell.CELL_TYPE_ERROR:
                          value = "";
                          break;

                      case HSSFCell.CELL_TYPE_BOOLEAN:
                          value = (cell.getBooleanCellValue() == true ? "Y": "N");
                          break;
                      default:
                          value = "";
                      }
                   }
                   if (headCell != null) {
                       // 注意:一定要设成这个,否则可能会出现乱码
                       //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                       switch (headCell.getCellType()) {
                       case HSSFCell.CELL_TYPE_STRING:
                           headV = headCell.getStringCellValue();
                           break;
                       case HSSFCell.CELL_TYPE_NUMERIC:
                           if (HSSFDateUtil.isCellDateFormatted(headCell)) {
                              Date date = headCell.getDateCellValue();
                              if (date != null) {
                                  headV = new SimpleDateFormat("yyyy-MM-dd").format(date);
                              } else {
                                  headV = "";
                              }
                           } else {
                              value = new DecimalFormat("0").format(headCell.getNumericCellValue());
                           }
                           break;
                       case HSSFCell.CELL_TYPE_FORMULA:
                           // 导入时如果为公式生成的数据则无值
                           if (!headCell.getStringCellValue().equals("")) {
                               headV = cell.getStringCellValue();
                           } else {
                               headV = cell.getNumericCellValue() + "";
                           }
                           break;

                       case HSSFCell.CELL_TYPE_BLANK:
                           break;

                       case HSSFCell.CELL_TYPE_ERROR:
                           value = "";
                           break;

                       case HSSFCell.CELL_TYPE_BOOLEAN:
                           headV = (cell.getBooleanCellValue() == true ? "Y": "N");
                           break;
                       default:
                           headV = "";
                       }
                    }
                   if (columnIndex == 0 && value.trim().equals("")) {
                      break;
                   }
                   hasValue = true;
                   tempMap.put(new String(ComUtil.rightTrim(headV)),new String(ComUtil.rightTrim(value)));
                }
               if (hasValue) {
                   tempMaps.add(tempMap);
               }
            }
            rsMap.put(wb.getSheetName(sheetIndex), tempMaps);
        }
        in.close();
        //把bm0的格式转为通用map的格式而非list
        rsMap.put("bm0", ((List)rsMap.get("bm0")).get(0));
        return rsMap;
     }
    
    //根据map还原为btl 
    public static BTLDAO getBtlByExcelMap(String rule,Map rsMaps) throws Exception {
        BTLDAO btl=new BTLDAO();
        BtlModule0 bi;
        StringBuilder buf = new StringBuilder();
        String cutStr = "";
        int cutSumCt = 1;//总循环次数
        int mapW = 0, mapH = 0, i,j;
        JSONObject row;
        List<DefRule> rs;
        Map biMap = null;
        Object rsO = null;
        List list;
       
        { //得到基础信息 
            cutStr = "bm0";
            row = getInfoByRootName(rule, cutStr);
            rs = getDefRuleInfosByRow(row);
            bi = new BtlModule0();
            biMap =  (Map) (rsMaps.get(cutStr));
            bi=(BtlModule0) ComUtil.mapToJBean(BtlModule0.class, biMap);
            btl.setBm0(bi);
            biMap = ComUtil.JBeanToMap(bi);
        }
        { //重复读取所有基本信息
            Object[] objects = new Object[] { (new BtlModule1()), (new BtlModule2()), (new BtlModule3()), (new BtlModule4()), (new BtlModule5()), (new BtlModule6()), (new BtlModule7()), (new BtlModule8()), (new BtlModule9()), (new BtlModule10()), (new BtlModule11()), (new BtlModule12()), (new BtlModule13()), (new BtlModule14()), (new BtlModule15()), (new BtlModule16()), (new BtlModule17()),
                    (new BtlModule18()), (new BtlModule19()), (new BtlModule20()) };
            String[] cutStrs = new String[] { "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" };
            for (i = 0; i < cutStrs.length; i++) {
                row = getInfoByRootName(rule, cutStrs[i]);
                if (row != null) { //List<DefRule> rs, List list,Map map
                    rs = getDefRuleInfosByRow(row);
                    list=(List)rsMaps.get(cutStrs[i]);
                   
                   // getBtlMoudleList(List<DefRule> rs, List list,Map map)
                    ComUtil.setVal(btl, "set" + ComUtil.UpperInitial(cutStrs[i]),  getBtlMoudleList(rs,list,objects[i]));
                    //ComUtil.setVal(btl, "set" + ComUtil.UpperInitial(cutStrs[i]), rsMap.get("T"));
                
                
                }
            }
        }
        return btl;
    }
}
BTLTooL转化类
package code;

/**
 * 资源常量
 * 
 * @xietansheng
 */
public interface Config {

    
    


    //TODO
    /**
     * Preferences 本地存储相关
     */
    public static interface Rules {

        public static final String GG1_RULE = "src/resource/rule/rule_btl_gg1.xml";
        public static final String WC4_RULE = "src/resource/rule/rule_btl_wc4.xml";

    }
    
    public static interface Btls {

        public static final String GG1_BTL = "src/resource/btl/gg1.btl";
        public static final String WC4_BTL = "src/resource/btl/wc4.btl";

    }
    
    public static interface Imgs {

        public static final String BG_JPG = "resource/img/bg.jpg";

    }
    
    public static interface Infos {
        public static final String INFO_WISH = "加油!";
        public static final String INFO_VERSION="1.0";
        public static final String INFO_AUTHER="作者:黑狱 协助者:bwucaca ";
        
    }

}
Config配置类

mod终究不是正途,就到这里吧.

剩下一段时间将整合这个项目,将fb的格式改为通用加载,同时增加对将荣地图的直接转化等功能

-------------------------------更新线--------------------------

发现size为4的时候长度应该是short,size为8的时候是Integer.我的里面写反了..emmmm

------------------------------更新线---------------------------

 我今天又花了一天,研究世界征服者4,我已经在这个游戏上研究了三周了,做游戏的mod真的没有价值,我过去的研究也就截止于世界征服者3,看到了4我想起了我曾经的世2,抱歉。真的不能再花精力对这些mod研究了。我得创造属于我自己的价值,而不是最后慢慢的老去。  -6.8

 -----------------------------2020 8 28----------------------------

后续有人使用了编辑器去做了一个mod,因为是可以上将领的缘故,整个游戏变成了养将游戏.在我看来,所有的挑战可以通过上将来解决.这已经不是策略游戏了.只是披着大地图皮的将领无双游戏.他做的所有战役,内容都因为可以养将上将而毫无意义,他们没救了.

 

posted on 2019-05-26 18:41  黑狱  阅读(916)  评论(0编辑  收藏  举报