creator加载表格数据

准备做一个数据比较多的经营类游戏,数据太多了不想自己填,所以就看了一下表格转化。找到了几种方法,分享一下。

首先要对表格编码处理,如果是excel存储的其他格式的名字,比如xlsx什么的,在excel中更改一下格式。右上角选择另存为creator加载表格数据_第1张图片

选择其他格式,在格式类型中选择csv,点击保存就可以了。

creator加载表格数据_第2张图片

最好再用notepad++将文件的编码改成utf-8,防止乱码。

第一种:直接将csv表格放在resources目录下,通过cc.loader.loadRes加载表格,然后再转化成json格式。这种方式需要异步加载。还需要导入一个转换的js工具。这个js工具是我在creator论坛上看到别人分享的,代码如下:

(function() {
'use strict';
var ESCAPE_DELIMITERS = ['|', '^'],
CELL_DELIMITERS = [',', ';', '\t', '|', '^'],
LINE_DELIMITERS = ['\r\n', '\r', '\n'];

function isObject(object) {
var type = typeof object;
return type === 'function' || type === 'object' && !!object;
}
var isArray = Array.isArray || function(object) {
return toString.call(object) === '[object Array]';
}
function isString(object) {
return typeof object === 'string';
}
function isNumber(object) {
return !isNaN(Number(object));
}
function isBoolean(value) {
return value == false || value == true;
}
function isNull(value) {
return value == null;
}
function isPresent(value) {
return value != null;
}

function fallback(value, fallback) {
return isPresent(value) ? value : fallback;
}

function forEach(collection, iterator) {
for (var _i = 0, _len = collection.length; _i < _len; _i += 1) {
if (iterator(collection[_i], _i) === false) break;
}
}

function buildCell(index) {
return 'attrs[' + index + ']';
}

function castCell(value, index) {
if (isNumber(value)) {
return 'Number(' + buildCell(index) + ')';
} else if (isBoolean(value)) {
return 'Boolean(' + buildCell(index) + ' == true)';
} else {
return 'String(' + buildCell(index) + ')';
}
}

function buildConstructor(cast, values, attrs) {
var definition = [];
if (arguments.length == 2) {
if (cast) {
if (isArray(cast)) {
forEach(values, function(value, index) {
definition.push(cast[index] + '(' + buildCell(index) + ')');
});
} else {
forEach(values, function(value, index) {
definition.push(castCell(value, index));
});
}
} else {
forEach(values, function(value, index) {
definition.push(buildCell(index));
});
}
definition = 'return [' + definition.join(',') + ']';
} else {
if (cast) {
if (isArray(cast)) {
forEach(values, function(value, index) {
definition.push('"' + attrs[index] + '": ' + cast[index] + '(' + buildCell(index) + ')');
});
} else {
forEach(values, function(value, index) {
definition.push('"' + attrs[index] + '": ' + castCell(value, index));
});
}
} else {
forEach(values, function(value, index) {
definition.push('"' + attrs[index] + '": ' + buildCell(index));
});
}
definition = 'return {' + definition.join(',') + '}';
}
return new Function('attrs', definition);
}

function detectDelimiter(string, delimiters) {
var count = 0,
detected;

forEach(delimiters, function(delimiter) {
  var needle = delimiter,
      matches;
  if (ESCAPE_DELIMITERS.indexOf(delimiter) != -1) {
    needle = '\\' + needle;
  }
  matches = string.match(new RegExp(needle, 'g'));
  if (matches && matches.length > count) {
    count = matches.length;
    detected = delimiter;
  }
});
return (detected || delimiters[0]);
}

var CSV = (function() {
function CSV(data, options) {
if (!options) options = {};

  if (isArray(data)) {
    this.mode = 'encode';
  } else if (isString(data)) {
    this.mode = 'parse';
  } else {
    throw new Error("Incompatible format!");
  }

  this.data = data;

  this.options = {
    header: fallback(options.header, false),
    cast: fallback(options.cast, true)
  }

  var lineDelimiter = options.lineDelimiter || options.line,
      cellDelimiter = options.cellDelimiter || options.delimiter;

  if (this.isParser()) {
    this.options.lineDelimiter = lineDelimiter || detectDelimiter(this.data, LINE_DELIMITERS);
    this.options.cellDelimiter = cellDelimiter || detectDelimiter(this.data, CELL_DELIMITERS);
    this.data = normalizeCSV(this.data, this.options.lineDelimiter);
  } else if (this.isEncoder()) {
    this.options.lineDelimiter = lineDelimiter || '\r\n';
    this.options.cellDelimiter = cellDelimiter || ',';
  }
}

function invoke(method, constructor, attributes) {
  method(new constructor(attributes));
}

function normalizeCSV(text, lineDelimiter) {
  if (text.slice(-lineDelimiter.length) != lineDelimiter) text += lineDelimiter;
  return text;
}

CSV.prototype.set = function(setting, value) {
  return this.options[setting] = value;
}

CSV.prototype.isParser = function() {
  return this.mode == 'parse';
}

CSV.prototype.isEncoder = function() {
  return this.mode == 'encode';
}

CSV.prototype.parse = function(callback) {
  if (this.mode != 'parse') return;

  if (this.data.trim().length === 0) return [];

  var data = this.data,
      options = this.options,
      header = options.header,
      current = { cell: '', line: [] },
      flag, record, response;

  if (!callback) {
    response = [];
    callback = function(record) {
      response.push(record);
    }
  }

  function resetFlags() {
    flag = { escaped: false, quote: false, cell: true };
  }
  function resetCell() {
    current.cell = '';
  }
  function resetLine() {
    current.line = [];
  }

  function saveCell(cell) {
    current.line.push(flag.escaped ? cell.slice(1, -1).replace(/""/g, '"') : cell);
    resetCell();
    resetFlags();
  }
  function saveLastCell(cell) {
    saveCell(cell.slice(0, 1 - options.lineDelimiter.length));
  }
  function saveLine() {
    if (header) {
      if (isArray(header)) {
        record = buildConstructor(options.cast, current.line, header);
        saveLine = function() { invoke(callback, record, current.line); };
        saveLine();
      } else {
        header = current.line;
      }
    } else {
      if (!record) {
        record = buildConstructor(options.cast, current.line);
      }
      saveLine = function() { invoke(callback, record, current.line); };
      saveLine();
    }
  }

  if (options.lineDelimiter.length == 1) saveLastCell = saveCell;

  var dataLength = data.length,
      cellDelimiter = options.cellDelimiter.charCodeAt(0),
      lineDelimiter = options.lineDelimiter.charCodeAt(options.lineDelimiter.length - 1),
      _i, _c, _ch;

  resetFlags();

  for (_i = 0, _c = 0; _i < dataLength; _i++) {
    _ch = data.charCodeAt(_i);

    if (flag.cell) {
      flag.cell = false;
      if (_ch == 34) {
        flag.escaped = true;
        continue;
      }
    }

    if (flag.escaped && _ch == 34) {
      flag.quote = !flag.quote;
      continue;
    }

    if ((flag.escaped && flag.quote) || !flag.escaped) {
      if (_ch == cellDelimiter) {
        saveCell(current.cell + data.slice(_c, _i));
        _c = _i + 1;
      } else if (_ch == lineDelimiter) {
        saveLastCell(current.cell + data.slice(_c, _i));
        _c = _i + 1;
        saveLine();
        resetLine();
      }
    }
  }

  if (response) {
    return response;
  } else {
    return this;
  }
}

function serializeType(object) {
  if (isArray(object)) {
    return 'array';
  } else if (isObject(object)) {
    return 'object';
  } else if (isString(object)) {
    return 'string';
  } else if (isNull(object)) {
    return 'null';
  } else {
    return 'primitive';
  }
}

CSV.prototype.serialize = {
  "object": function(object) {
    var that = this,
        attributes = Object.keys(object),
        serialized = Array(attributes.length);
    forEach(attributes, function(attr, index) {
      serialized[index] = that[serializeType(object[attr])](object[attr]);
    });
    return serialized;
  },
  "array": function(array) {
    var that = this,
        serialized = Array(array.length);
    forEach(array, function(value, index) {
      serialized[index] = that[serializeType(value)](value);
    });
    return serialized;
  },
  "string": function(string) {
    return '"' + String(string).replace(/"/g, '""') + '"';
  },
  "null": function(value) {
    return '';
  },
  "primitive": function(value) {
    return value;
  }
}

CSV.prototype.encode = function(callback) {
  if (this.mode != 'encode') return;

  if (this.data.length == 0) return '';

  var data = this.data,
      options = this.options,
      header = options.header,
      sample = data[0],
      serialize = this.serialize,
      offset = 0,
      attributes, response;

  if (!callback) {
    response = Array(data.length);
    callback = function(record, index) {
      response[index + offset] = record;
    }
  }

  function serializeLine(record) {
    return record.join(options.cellDelimiter);
  }

  if (header) {
    if (!isArray(header)) {
      attributes = Object.keys(sample);
      header = attributes;
    }
    callback(serializeLine(serialize.array(header)), 0);
    offset = 1;
  }

  var recordType = serializeType(sample),
      map;

  if (recordType == 'array') {
    if (isArray(options.cast)) {
      map = Array(options.cast.length);
      forEach(options.cast, function(type, index) {
        map[index] = type.toLowerCase();
      });
    } else {
      map = Array(sample.length);
      forEach(sample, function(value, index) {
        map[index] = serializeType(value);
      });
    }
    forEach(data, function(record, recordIndex) {
      var serializedRecord = Array(map.length);
      forEach(record, function(value, valueIndex) {
        serializedRecord[valueIndex] = serialize[map[valueIndex]](value);
      });
      callback(serializeLine(serializedRecord), recordIndex);
    });
  } else if (recordType == 'object') {
    attributes = Object.keys(sample);
    if (isArray(options.cast)) {
      map = Array(options.cast.length);
      forEach(options.cast, function(type, index) {
        map[index] = type.toLowerCase();
      });
    } else {
      map = Array(attributes.length);
      forEach(attributes, function(attr, index) {
        map[index] = serializeType(sample[attr]);
      });
    }
    forEach(data, function(record, recordIndex) {
      var serializedRecord = Array(attributes.length);
      forEach(attributes, function(attr, attrIndex) {
        serializedRecord[attrIndex] = serialize[map[attrIndex]](record[attr]);
      });
      callback(serializeLine(serializedRecord), recordIndex);
    });
  }

  if (response) {
    return response.join(options.lineDelimiter);
  } else {
    return this;
  }
}

CSV.prototype.forEach = function(callback) {
  return this[this.mode](callback);
}

return CSV;
})();

CSV.parse = function(data, options) {
return new CSV(data, options).parse();
}

CSV.encode = function(data, options) {
return new CSV(data, options).encode();
}

CSV.forEach = function(data, options, callback) {
if (arguments.length == 2) {
callback = options;
}
return new CSV(data, options).forEach(callback);
}

if (typeof define === "function" && define.amd) {
define('CSV', [], function() {
return CSV;
});
} else if (typeof module === "object" && module.exports) {
module.exports = CSV;
} else if (window) {
window.CSV = CSV;
}
})();

使用方法就是:

 cc.loader.loadRes("data/abc", function (err, res) {

            console.log(res);

            console.log(typeof(res));

            var _csv = new Csv(res.text);

            var _con = _csv.parse();

            console.log(_con);

  });

方法亲测有效,后台打印了表格的内容。但是输出的格式不太对,是每行算一个数组,不像json那种键值一一对应的。

表格内容:

creator加载表格数据_第3张图片

加载后后台输出:

creator加载表格数据_第4张图片

期望值应该是id:2 ,number:0这样子,不过也算是读出来了,需要再多一步重组键值。

 

第二种:使用npm的csvtojson工具,默认电脑有nodejs环境,如果没有,可以去官网下载安装。https://nodejs.org/zh-cn/download/。在电脑中安装csvtojson工具。window + r  ,cmd打开命令行。输入 csvtojson i -g csvtojson,回车等待安装完成即可。

使用:打开存储csv表格的目录,按下shift点击右键,选择在此处打开命令窗口,输入 csvtojson fileName.csv > convertName.json  点击回车就可以了。例如要转换的表格名为abc.csv,期望转换为abc.json,那么就是输入 csvtojson abc.csv > abc.json。回车之后就会在目录下看到多了一个abc.json,这就是我们转换后的json文件。

creator加载表格数据_第5张图片

转换前:creator加载表格数据_第6张图片

转换后:

creator加载表格数据_第7张图片

第三种方法:

同样是npm的工具,csvtojs,安装命令:npm install -g csvtojs。

转换同样是在表格目录下用命令行,csvtojs ./fileName.csv。比如要转换abc.csv,只需要输入csvtojs ./abc.csv,然后回车就可以了。

除了上边这三种,也可以用在线转换工具,百度搜索就可以了

你可能感兴趣的:(creator加载表格数据)