Excel 读写

Excel 读写_第1张图片

using System.Collections;
using System.Collections.Generic;
using OfficeOpenXml;
using System.IO;
using UnityEngine;


public class ExcelTest : MonoBehaviour
{
    void Start()
    {
        string _filePath = Application.streamingAssetsPath + "/学生信息.xlsx";

        WriteExcel(_filePath);
        ReadExcel(_filePath);
    }

    void WriteExcel(string _filePath)
    {
        string _sheetName = "详情";
        FileInfo fileInfo = new FileInfo(_filePath);
        if (fileInfo.Exists)
        {
            fileInfo.Delete();   //删除旧文件,并创建一个新的 excel 文件。
            fileInfo = new FileInfo(_filePath);
        }

        //通过ExcelPackage打开文件
        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            //在 excel 空文件添加新 sheet,并设置名称。
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(_sheetName);

            //添加列名
            worksheet.Cells[1, 1].Value = "学号";
            worksheet.Cells[1, 2].Value = "姓名";
            worksheet.Cells[1, 3].Value = "性别";

            //添加一行数据
            worksheet.Cells[2, 1].Value = 100001;
            worksheet.Cells[2, 2].Value = "张三";
            worksheet.Cells[2, 3].Value = "男";

            //添加一行数据
            worksheet.Cells[3, 1].Value = 100002;
            worksheet.Cells[3, 2].Value = "李四";
            worksheet.Cells[3, 3].Value = "女";

            //添加一行数据
            worksheet.Cells[4, 1].Value = 120033;
            worksheet.Cells[4, 2].Value = "Saw";
            worksheet.Cells[4, 3].Value = "男";

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

    void ReadExcel(string _filePath)
    {
        //获取Excel文件的信息
        FileInfo fileInfo = new FileInfo(_filePath);
        if (!fileInfo.Exists)
            return;

        using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
        {
            ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[1];
            int rowCount = worksheet.Dimension.End.Row;
            int columnCount = worksheet.Dimension.End.Column;
            for (int i = 0; i < rowCount; i++)//End.Row获得当前表格的最大行数
            {
                string str = null;
                for (int j = 0; j < columnCount; j++)
                {
                    str += worksheet.Cells[i + 1, j + 1].Value.ToString();
                    if (j < columnCount - 1)
                    {
                        str += ",";
                    }
                }
                Debug.Log($"ReadExcel: line {i + 1} " + str);
            }
        }
    }
}

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