大家好,我是小bo,最近用unity写了一个读写execl的小工具,这里记录下来,帮助大家少进坑。
首先列举一下参考博文:
https://blog.csdn.net/yupu56/article/details/50580277
https://blog.csdn.net/luoyikun/article/details/81012065
http://www.xuanyusong.com/archives/2429
所需库(可在参考博文中下载):
备注:
1.你的unity版本是多少,去对应的安装目录中取dll
2.System.Data.dll 在D:\Program Files\Unity2017.2\Editor\Data\Mono\lib\mono\2.0
3.I18N开头的dll 在 D:\Program Files\Unity2017.2\Editor\Data\Mono\lib\mono\unity
读写代码:
void ReadExcel()
{
FileStream stream = File.Open (Application.dataPath + "/Test.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader (stream);
do{
// sheet name
Debug.Log(excelReader.Name);
while (excelReader.Read()) {
for (int i = 0; i < excelReader.FieldCount; i++) {
string value = excelReader.IsDBNull(i) ? "" : excelReader.GetString(i);
Debug.Log(value);
}
}
}while(excelReader.NextResult());
}
}
void WriteExcel()
{
string outputDir = Application.dataPath + "/Test.xlsx"
FileInfo newFile = new FileInfo(outputDir);
if (newFile.Exists)
{
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(outputDir);
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
//Add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Product";
worksheet.Cells[1, 3].Value = "Quantity";
worksheet.Cells[1, 4].Value = "Price";
worksheet.Cells[1, 5].Value = "Value";
//Add some items...
worksheet.Cells["A2"].Value = 12001;
worksheet.Cells["B2"].Value = "Nails";
worksheet.Cells["C2"].Value = 37;
worksheet.Cells["D2"].Value = 3.99;
worksheet.Cells["A3"].Value = 12002;
worksheet.Cells["B3"].Value = "Hammer";
worksheet.Cells["C3"].Value = 5;
worksheet.Cells["D3"].Value = 12.10;
worksheet.Cells["A4"].Value = 12003;
worksheet.Cells["B4"].Value = "Saw";
worksheet.Cells["C4"].Value = 12;
worksheet.Cells["D4"].Value = 15.37;
//save our new workbook and we are done!
package.Save();
}
}
yusong momo提醒的内容(本人手机上没有验证):
哦对,还有一句话忘说了,最好不要在程序运行时去动态解析这个Excel 。我的做法是把利用这个类库把Excel里面的数据读取出来,然后自己用File在去把数据写在别的文件中,方面以后加密拓展等等。
补充: 请大家切记,在游戏运行时不要去动态解析Excel,因为在手机上解析不了。。而且你需要把这个dll加在工程里面,最好的就是 先把Excel写入文件,。 运行的时候读取这个文件的方式来做。。