1.导入ExcelSDK:链接:https://pan.baidu.com/s/1LiU6Kaxmc9j6kbFoE9QMFA?pwd=dr78
提取码:dr78
2.挂载脚本,并运行unity
using Excel;
using OfficeOpenXml;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using UnityEngine;
public class RWExcel : MonoBehaviour {
// Use this for initialization
void Start () {
string path = Application.dataPath + "/入学信息.xlsx";
WriteExcel(path);
ReadExcel(path);
}
// Update is called once per frame
void Update () {
}
//向excel中写数据
public void WriteExcel(string path)
{
FileInfo fileInfo = new FileInfo(path);//创建
if (fileInfo.Exists)
{
fileInfo.Delete();
fileInfo = new FileInfo(path);
}
using (ExcelPackage ep = new ExcelPackage(fileInfo))//内置关闭流,打开Excel
{
ExcelWorksheet sheet = ep.Workbook.Worksheets.Add("学生表");
sheet.Cells["A1"].Value = "学号";//给指定表格赋值
sheet.Cells["B1"].Value = "姓名";
sheet.Cells["C1"].Value = "年龄";
sheet.Cells["A2"].Value = "001";//给指定表格赋值
sheet.Cells["B2"].Value = "张三";
sheet.Cells["C2"].Value = "17";
sheet.Cells["A3"].Value = "002";//给指定表格赋值
sheet.Cells["B3"].Value = "李四";
sheet.Cells["C3"].Value = "18";
ep.Save();
}
}
//读excel中的数据
public void ReadExcel(string path)
{
List<SkillInfo> skills = DoExcel.LoadRead(path);
for (int i = 0; i < skills.Count; i++)
{
print(skills[i].id + " " + skills[i].name + " " + skills[i].skill);
}
}
public DataSet DoRead(string path)
{
FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
IExcelDataReader readData = ExcelReaderFactory.CreateOpenXmlReader(fs);//Excel流解析
DataSet data = readData.AsDataSet();//数据读取完毕 data
readData.Close();//关闭读取任务
return data;
}
public List<Student> LoadRead(string path)
{
DataSet data = DoRead(path);
List<Student> list = new List<Student>();
int com = data.Tables[0].Columns.Count;//拿到列
int row = data.Tables[0].Rows.Count;//拿到行
for (int i = 0; i < row; i++)
{
Student info;
info.id = data.Tables[0].Rows[i][0].ToString();
info.name = data.Tables[0].Rows[i][1].ToString();
info.age = int.Parse( data.Tables[0].Rows[i][2].ToString());
list.Add(info);
}
return list;
}
}
public struct Student
{
public string id;
public string name;
public int age;
}
3.refresh刷新后可以看到excel和写入的数据
4.console控制台输出从excel表中读取的数据
注:以上方法适合unity2017版本
结语:合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。