Use Unity to plot data in Excel

 The Unity version used is Unity 2020.3.34f1c2 (64-bit)

1. Import the chart plug-in XCharts into Unity

2. Import ExcelPlugins

3. Set the xy data number of the original XCharts script to 0, otherwise it will be connected and displayed in the first paragraph

4. Read the Excel file, assign the first column to the x-axis, and the second column to the y-axis.

See Xcharts plug-in, ExcelPlugins and Excel files: https://download.csdn.net/download/weixin_44918645/86544011

code show as below:

using Excel;
using System.Data;
using System.IO;
using UnityEngine;
using XCharts.Runtime;

public class ExcelLineChart : MonoBehaviour
{     void Start()     {         //The code needs to set the size to dynamically add the chart         var chart = gameObject.GetComponent<LineChart>();         if (chart == null)         {             chart = gameObject.AddComponent<LineChart>() ;             chart.SetSize(1580, 300);//The code dynamically adds the chart and needs to set the size         }








        //Set the title:
        var title = chart.GetOrAddChartComponent<Title>();
        title.text = "Spectral Chart";

        //Set the path of the file to be read here
        string FilePath = Application.dataPath + "/Resources/Excel.xlsx";

        //Read the file
        FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);

        //读取Excel文件
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        DataSet result = excelReader.AsDataSet();

        int columns = result.Tables[0].Columns.Count;//列
        int rows = result.Tables[0].Rows.Count;//行

      
        //Set to display 20 numbers
        var xAxis = chart.GetOrAddChartComponent<XAxis>();
        xAxis.splitNumber = 10;

        var yAxis = chart.GetOrAddChartComponent<YAxis>();
        yAxis.splitNumber = 10;

        
        //Add data
        for (int i = 0; i < rows; i++)
        {             for (int j = 0; j < columns; j++)             {                 string nvalue = result.Tables[0].Rows[i][j]. ToString();                 //Print the contents of the Excel file                 Debug.Log(nvalue);                 if (j == 0)                     chart.AddXAxisData(nvalue);                 else







                    chart.AddData(0, double.Parse(nvalue));

            }
        }

    }
}

running result

 

Guess you like

Origin blog.csdn.net/weixin_44918645/article/details/126924041