13.打包到一個窗口工具(界限計划4 終)


此為實物界面圖

三個功能:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM