[Unity reads from Excel]

     When I was working on a project, I suddenly wanted to optimize the input method of data, and I didn't want to insert code line by line, which felt very low.

     So I thought of using excel to do it, first write the data in excel, then import it in batches, and a foreach can read the data into the data structure we want to maintain.

      Without further ado, let's see how to do it. First, you have to go to Excel's official website to download his dynamic link library: an Excel.dll, an ICSharpCode.SharpZipLib.dll, and then put them in the project directory, preferably under plugins.

Of course, this is what you will notice there is another thing called system.data, yes this is also the dll that we need to get.

However, this dll does not need to be downloaded. It belongs to .net. The source directory of Unity has it. I have to complain about Unity here. It is reasonable to add dependencies directly, but there will be a name that cannot be found. Space bug, anyway, look for ctrl+f in his original directory, and copy this dll to the project directory.

Ok, the next step is to code.

First is the reference to the namespace:

using UnityEngine;
using System.Collections;
using Excel;
using System.Data;
using System.IO;
using System.Collections.Generic;
Then you need to define a structure of your own, which depends on what you put in your excel sheet. My excel sheet only has two properties per row, so I defined:
public struct DepenceTableData
	{
		public string word;
		public string instruct;
	};
Then we first read the file into a dataset-type variable:

static DataSet ReadExcel(string path)  
		{  
			FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);  
			IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);  
			DataSet result = excelReader.AsDataSet();  
			return result;  
		}
Next, the main attribute for us is table[0] under the dataset, which records the real data, as well as some information about the total number of rows and columns:
public static List<DepenceTableData> Load(string path)
		{
			List<DepenceTableData> _data = new List<DepenceTableData> ();
			DataSet resultds = ReadExcel (path);
			int columns = resultds.Tables[0].Columns.Count;
			int rows = resultds.Tables[0].Rows.Count;
			for (int i = 1; i < rows; i++)
			{
				DepenceTableData temp_data;
				temp_data.instruct = resultds.Tables [0].Rows [i] [0].ToString();
				temp_data.word = resultds.Tables [0].Rows [i] [1].ToString ();
				_data.Add (temp_data);
			}
			return _data;
		}

The index after .rows can be understood as a two-dimensional array.

Effect picture:

Here is my excel:




Then write the linked list to the console:


The screenshot is not finished, but it can be seen that all the information is output.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325803313&siteId=291194637