Unity读取写入Excel

1.在Plugins中放入dll,118开头的dll在Unity安装目录下(C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity)

Unity读取写入Excel_第1张图片2.写Excel

public void WriteExcel()
    {
        //文件地址
        FileInfo newFile = new FileInfo(Application.dataPath + "/test.xlsx");
        //数据操作
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            //增加数据操作(重点在于这条操作语句与初次创建添加数据不同)
            ExcelWorksheet worksheet = package.Workbook.Worksheets["test"];
            if(worksheet == null)
            {
                worksheet = package.Workbook.Worksheets.Add("test");
            }

            //写首行
            worksheet.Cells[1, 1].Value = "编号";
            worksheet.Cells[1, 2].Value = "姓名";
            worksheet.Cells[1, 3].Value = "组号";

            //添加第二行数据
            worksheet.Cells[2, 1].Value = "001";
            worksheet.Cells[2, 2].Value = "王大于";
            worksheet.Cells[2, 3].Value = "1";

            //添加第三行数据
            worksheet.Cells[3, 1].Value = "002";
            worksheet.Cells[3, 2].Value = "李云香";
            worksheet.Cells[3, 3].Value = "1";

            //保存
            package.Save();
        }
    }

3.读Excel

public void ReadExcel()
    {
        //加载文件
        FileStream fileStream = File.Open(Application.dataPath + "/test.xlsx", FileMode.Open, FileAccess.Read);
        IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
        DataSet result = excelDataReader.AsDataSet();

        int columns = result.Tables[0].Columns.Count; 
        int rows = result.Tables[0].Rows.Count;
		Debug.Log("共有:" + columns + "列 " + rows + "行");
		
        //第一行为表头,不读取。没有表头从0开始(获取数据)
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                // 获取表格中指定行指定列的数据 
                string value = result.Tables[0].Rows[i][j].ToString();
                Debug.Log(value);
            }
        }
        fileStream.Close();
    }

你可能感兴趣的:(Unity,unity,Excel)