您的位置:首页 > 移动开发 > Unity3D

Unity 读取CSV与Excel

2015-05-11 16:54 363 查看
  前几天看到我们在游戏中需要动态加载某些角色的游戏策划值,关于这个问题怎么解决呢?其实办法很多种,归根到底,就是数据的读取。我们可以想到的存储数据的载体有很多。例如:txt,xml,csv,excel。甚至可以使用Sqlite,Mysql,Sqlserver等!这都不是问题!那么我们今天学习下CSV文件和Excel的读取。废话不多说了,开始了!

1.建个空的项目!

using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using Excel;
using System.Data;
using UnityEngine.UI;

public class NewBehaviourScript : MonoBehaviour
{
public Text readData;
void Start ()
{
XLSX();
}

void XLSX()
{
FileStream stream = File.Open(Application.dataPath + "/UserLevel.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

DataSet result = excelReader.AsDataSet();

int columns = result.Tables[0].Columns.Count;
int rows = result.Tables[0].Rows.Count;

for(int i = 0;  i< rows; i++)
{
for (int j = 0; j < columns; j++)
{
string nvalue = result.Tables[0].Rows[i][j].ToString();
Debug.Log(nvalue);
if (i > 0)
{
readData.text += "\t\t" + nvalue;
}
else
{
readData.text +="   \t" + nvalue;
}
}
readData.text += "\n";
}
}

}


View Code



搞定收工!

PS:可以以数据集的形式存储读取到的二维表格,然后可直接以二维数组的形式获取各个元组的信息!

作为数据集进行存储

DataSet result = excelReader.AsDataSet();

取得数据集中第一张表格的行的数目
int rows = result.Tables[0].Rows.Count;

取得数据集中第一张表格的列的数目

int columns = result.Tables[0].Columns.Count;

直接对行列操作:

result.Tables[0].Rows[i][j].

百度网盘:http://pan.baidu.com/s/1kTGIGS3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: