遊戲數據讀取寫入:Java操作Excel與Json文件

前言:近期弄了弄關卡類型的小遊戲,發現遊戲數據一般都是json格式存儲的,json文件對於計算機讀寫來說確實比較簡單方便,但大量的遊戲數據對於人工錄入來說確實麻煩,所以嘗試依靠poi將數據操作轉爲對excel文件操作,請看~(下文不包括遊戲具體實現,只有如何操作數據..)

準備知識

  • 新建一個maven項目
  • 瞭解 poi 和 fastJson 基礎理論

實現效果

1. pom文件

    <dependencies>

        <!--03 版本 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>

        <!--07版本-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>

        <!--測試-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
        </dependency>

        <!--io流-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

    </dependencies>

2. 封裝工具類

    /**
     * 大數據寫 快速寫重構
     * @param fileName
     * @param sheetName
     * @param rowBeginIndex
     * @param row
     * @param col
     * @param path
     * @return
     */
    public boolean writeExcelByPoiSXSSFBigData(
            String fileName, String sheetName,
            int rowBeginIndex, List<String> row,
            List<List<Object>> col,
            String path
    ) throws IOException{
        // 處理文件後綴名 即 路徑
        fileName += ".xlsx";
        path += fileName;

        // 創建表格
        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet(sheetName);
        // 起始行
        Row row1 = sheet.createRow(rowBeginIndex);
        int rowLen = row.size();
        for (int i = 0; i < rowLen; i++) {
            // 第一行 第幾列 初始化
            row1.createCell(i).setCellValue(row.get(i));
        }

        // 文件內容
        // 內容記錄 行數
        int colLen = col.size();
        for (int i = rowBeginIndex + 1; i < colLen + rowBeginIndex + 1; i++) {
            // 多少行內容
            Row temp = sheet.createRow(i);
            for (int j = 0; j < col.get(i - rowBeginIndex - 1).size(); j++) {
                // 每行內容寫入文件
                temp.createCell(j).setCellValue(col.get(i - rowBeginIndex - 1).get(j).toString());
            }
        }

        // IO操作
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            workbook.write(out);// 寫文件
            //清空臨時文件
            ((SXSSFWorkbook)workbook).dispose();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            out.close();
            workbook.close();
        }
        return true;
    }


    /***
     *
     * 解決poi 單元格數據類型轉換問題
     * @param cell 單元格
     * @return Object 單元格值
     * @author 掌灬紋
     * @since 2021/3/1
     */
    public Object readExcelAllTypes(Cell cell){
        // 獲取單元格枚舉類型
        Object value = "";
        CellType cellType = cell.getCellType();

        if (null != cellType){
            // 類型非空
            switch (cellType){
                case STRING:
                    value = cell.getStringCellValue();
                    break;
                case BOOLEAN:
                    value = cell.getBooleanCellValue();
                    break;
                case NUMERIC: // 日期 數字處理
                    if (DateUtil.isCellDateFormatted(cell)){
                        // 日期格式
                        DateTime dateTime = new DateTime(cell.getDateCellValue());
                        value = dateTime.toString("yyyy-MM-dd");
                    }else {
                        // 數字 轉爲字符串處理 防止科學計數法
                        cell.setCellType(CellType.STRING);
                        value = cell.getStringCellValue();
                    }
                    break;
                case BLANK: // 空格
                    value = "";
                    break;
                case ERROR:
                    System.out.println("error: Error Type");
                    break;
            }
        }
        return value;
    }

3.數據轉化(json->excel)

/**
 *
 * 遊戲數據:json格式文件 轉換 excel表格
 * @author 掌灬紋
 */
public class JsonToExcel {
    public static void main(String[] args) throws IOException {
        // 讀取json文件
        String url = "E:\\";
        String json = getJson(url + "level.json");
        //System.out.println(json);

        List<Level> levelList = new ArrayList<Level>();

        // 解析json字符串
        JSONObject jsonObject = JSON.parseObject(json);
        // 獲取關卡總數
        Integer levelCount = jsonObject.getInteger("levelCount");
        for (int i = 1; i <= levelCount; i++){
            // 獲取每關內容
            JSONObject temp = JSON.parseObject(jsonObject.get("level").toString());
            //System.out.println(temp.get(i));
            // 封裝java對象
            Level curLev = initCurLevel(JSON.parseObject(temp.get(i).toString()), i);
            levelList.add(curLev);
        }

        // 寫excel
        // 行初始化
        List<String> row = new ArrayList<String>();
        row.add("level");
        row.add("content");
        row.add("allRow");
        row.add("allCol");
        row.add("heroRow");
        row.add("heroCol");
        row.add("allTime");
        // 內容初始化
        List<List<Object>> col = new ArrayList<List<Object>>();
        for (Level e:levelList) {
            List<Object> temp = new ArrayList<Object>();
            temp.add(e.getId());
            temp.add(contentToArray(e.getContent()));
            temp.add(e.getAllRow());
            temp.add(e.getAllCol());
            temp.add(e.getHeroRow());
            temp.add(e.getHeroCol());
            temp.add(e.getAllTime() == null ? 60 : e.getAllTime());
            col.add(temp);
        }
        new PoiUtils().writeExcelByPoiSXSSFBigData(
                "[excel]遊戲數據" + System.currentTimeMillis(),
                "遊戲數據", 0,row,col,url
        );

    }

    /**
     * 數組內容轉換 object 爲 整形數組 在轉爲字符串
     * @param content
     * @return
     */
    private static String contentToArray(Object[] content) {
        int len = content.length;
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < len; i++) {
            res.append((Integer) (content[i]));
            if (i != len-1){
                res.append(", ");
            }
        }
        return res.toString();
    }

    /**
     * 初始化當前關卡對象
     * json 轉 Java對象
     * @param parseObject
     * @param index 當前關卡數
     * @return
     */
    private static Level initCurLevel(JSONObject parseObject, int index) {
        Level level = new Level();
        level.setId(index);
        level.setContent(parseObject.getJSONArray("content").toArray());
        level.setAllCol(parseObject.getInteger("allCol"));
        level.setAllRow(parseObject.getInteger("allRow"));
        level.setAllTime(parseObject.getInteger("allTime"));
        level.setHeroCol(parseObject.getInteger("heroCol"));
        level.setHeroRow(parseObject.getInteger("heroRow"));
        return level;

    }


    /**
     * 讀取本地 json文件
     * @param url
     * @return
     */
    private static String getJson(String url) {
        String result = "";

        File file = null;
        Reader reader = null;
        try {
            file = new File(url);
            reader = new InputStreamReader(new FileInputStream(file),"UTF-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            result = sb.toString();
            // 關閉流
            reader.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }


        return result;
    }
}

~彩蛋:讀取數據生成的遊戲關卡界面
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章