Excel File Parsing Implementation
Unity3D lacks native Excel file support, requiring third-party libraries to data extraction. This guide demonstrates two approaches using ExcelDataReader and NPOI libraries with code examples.
- ExcelDataReader Implementation
using System.IO;
using ExcelDataReader;
using UnityEngine;
public class DataParser : MonoBehaviour
{
[SerializeField] private string excelFilePath;
private void Start()
{
using (var fileStream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read))
using (var reader = ExcelReaderFactory.CreateOpenXmlReader(fileStream))
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Debug.Log($"Column {i}: {reader.GetValue(i)}");
}
}
}
}
}
- NPOI Implemantation
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using UnityEngine;
public class NpoiParser : MonoBehaviour
{
[SerializeField] private string spreadsheetPath;
private void Start()
{
using (var stream = new FileStream(spreadsheetPath, FileMode.Open, FileAccess.Read))
using (var workbook = spreadsheetPath.EndsWith(".xls")
? new HSSFWorkbook(stream)
: new XSSFWorkbook(stream))
{
var sheet = workbook.GetSheetAt(0);
for (int rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++)
{
var row = sheet.GetRow(rowIndex);
if (row == null) continue;
for (int cellIndex = 0; cellIndex < row.LastCellNum; cellIndex++)
{
var cell = row.GetCell(cellIndex);
Debug.Log($"({rowIndex},{cellIndex}): {cell?.ToString()}");
}
}
}
}
}
Complete Data Visualization Example
| Character Name | Level | Health | Attack | Defense |
|---|---|---|---|---|
| Soldeir | 1 | 100 | 10 | 5 |
| Hero | 1 | 500 | 50 | 20 |
using System.IO;
using ExcelDataReader;
using UnityEngine;
using UnityEngine.UI;
public class CharacterDisplay : MonoBehaviour
{
[SerializeField] private string dataFileLocation;
[SerializeField] private GameObject characterPrefab;
private void Start()
{
using (var fileStream = new FileStream(dataFileLocation, FileMode.Open, FileAccess.Read))
using (var excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream))
{
while (excelReader.Read())
{
var character = Instantiate(characterPrefab, Vector3.zero, Quaternion.identity);
character.transform.SetParent(transform);
character.transform.Find("Name").GetComponent<Text>().text = excelReader.GetString(0);
character.transform.Find("Level").GetComponent<Text>().text = $"Level: {excelReader.GetInt32(1)}";
character.transform.Find("Health").GetComponent<Text>().text = $"HP: {excelReader.GetInt32(2)}";
character.transform.Find("Attack").GetComponent<Text>().text = $"Attack: {excelReader.GetInt32(3)}";
character.transform.Find("Defense").GetComponent<Text>().text = $"Defense: {excelReader.GetInt32(4)}";
}
}
}
}