依賴EPPlus
獲取依賴可以閱讀:Nuget For Unity插件介紹_nugetforunity-CSDN博客
可以參閱該篇快速入門:在Unity中使用Epplus寫Excel_unity epplus-CSDN博客
下面是我封裝的幾個方法:
要在合適的時機配置許可證,比如你的工具類的靜態函數.建議使用版本7.7.1
#region Excel封裝,使用Eppluspublic class ExcelRowData{/// <summary>/// 來自那張表/// </summary>public string BelongSheetName { get; set; }/// <summary>/// 來自哪一行(從2開始,第一行為表頭)/// </summary>public int RowNumber { get; set; }/// <summary>/// key=列名 value=數據/// </summary>public Dictionary<string, string> Data { get; set; }}#region 讀/// <summary>/// 讀取 Excel 文件,返回所有工作表的數據(含行號)/// </summary>public static Dictionary<string, List<ExcelRowData>> ReadExcelAllSheets(string filePath){if (!File.Exists(filePath))throw new FileNotFoundException("Excel 文件不存在", filePath);var result = new Dictionary<string, List<ExcelRowData>>();using (var package = new ExcelPackage(new FileInfo(filePath))){foreach (var worksheet in package.Workbook.Worksheets){var sheetData = ReadWorksheet(worksheet);result[worksheet.Name] = sheetData;}}return result;}/// <summary>/// 讀取指定工作表的數據(含行號)/// </summary>public static List<ExcelRowData> ReadExcelSheet(string filePath, string sheetName){if (!File.Exists(filePath))throw new FileNotFoundException("Excel 文件不存在", filePath);using (var package = new ExcelPackage(new FileInfo(filePath))){var worksheet = package.Workbook.Worksheets[sheetName];if (worksheet == null)throw new ArgumentException($"未找到工作表:{sheetName}");return ReadWorksheet(worksheet);}}/// <summary>/// 讀取單個工作表的數據(第一行為表頭,返回包含行號的結構)/// </summary>private static List<ExcelRowData> ReadWorksheet(ExcelWorksheet worksheet){var result = new List<ExcelRowData>();if (worksheet.Dimension == null)return result;int rowCount = worksheet.Dimension.End.Row;int colCount = worksheet.Dimension.End.Column;var sheetName = worksheet.Name;// 讀取表頭var headers = new List<string>();for (int col = 1; col <= colCount; col++){var header = worksheet.Cells[1, col].Text.Trim();if (string.IsNullOrEmpty(header))throw new Exception($"表頭第 {col} 列為空,請檢查Excel文件格式。");headers.Add(header);}// 讀取數據行for (int row = 2; row <= rowCount; row++){var rowDict = new Dictionary<string, string>();for (int col = 1; col <= colCount; col++){string cellValue = worksheet.Cells[row, col].Text.Trim();if (string.IsNullOrEmpty(cellValue))throw new Exception($"工作表 '{worksheet.Name}' 第 {row} 行,第 {col} 列({headers[col - 1]})單元格為空,請檢查數據完整性。");string header = headers[col - 1];rowDict[header] = cellValue;}result.Add(new ExcelRowData { BelongSheetName = sheetName, RowNumber = row, Data = rowDict });}return result;}#endregion#region 寫/// <summary>/// 將單張表的數據寫入 Excel 文件(如果文件不存在會自動創建)/// </summary>/// <param name="sheetName">工作表名稱,不能為空或空白</param>/// <param name="rows">該表的數據行列表,不能為空且至少包含一行數據</param>/// <param name="filePath">可選,指定輸出文件路徑。如果為 null 或空,則默認保存到桌面“Excel”目錄下,并以當前時間戳+GUID命名文件</param>/// <exception cref="ArgumentException">當 sheetName 為空或 rows 為空時拋出異常</exception>public static void WriteExcelSingleSheet(string sheetName, List<ExcelRowData> rows, string filePath = null){if (string.IsNullOrWhiteSpace(sheetName))throw new ArgumentException("工作表名稱不能為空", nameof(sheetName));if (rows == null || rows.Count == 0)throw new ArgumentException("數據不能為空", nameof(rows));string desktopExcelPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Excel");Directory.CreateDirectory(desktopExcelPath);if (string.IsNullOrWhiteSpace(filePath)){filePath = Path.Combine(desktopExcelPath, $"Excel_{DateTime.Now:yyyyMMdd_HHmmss}_{Guid.NewGuid()}.xlsx");}using (var package = new ExcelPackage(filePath)){var ws = package.Workbook.Worksheets.Add(sheetName);// 寫表頭var headers = rows[0].Data.Keys.ToList();for (int col = 0; col < headers.Count; col++){ws.Cells[1, col + 1].Value = headers[col];}// 寫數據行for (int rowIndex = 0; rowIndex < rows.Count; rowIndex++){var rowData = rows[rowIndex].Data;int excelRow = rowIndex + 2;int colIndex = 1;foreach (var header in headers){rowData.TryGetValue(header, out string cellValue);ws.Cells[excelRow, colIndex].Value = cellValue;colIndex++;}}package.Save();}}/// <summary>/// 將多個表的數據寫入同一個 Excel 文件(如果文件不存在會自動創建)/// </summary>/// <param name="excelData">字典,key 為工作表名稱,value 為對應的該表數據行列表,字典不能為空且至少含有一個表數據</param>/// <param name="filePath">可選,指定輸出文件路徑。如果為 null 或空,則默認保存到桌面“Excel”目錄下,并以當前時間戳+GUID命名文件</param>/// <exception cref="ArgumentNullException">當 excelData 為 null 或為空時拋出異常</exception>public static void WriteExcelAllSheets(Dictionary<string, List<ExcelRowData>> excelData, string filePath = null){if (excelData == null || excelData.Count == 0)throw new ArgumentNullException(nameof(excelData));string desktopExcelPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Excel");Directory.CreateDirectory(desktopExcelPath);if (string.IsNullOrWhiteSpace(filePath)){filePath = Path.Combine(desktopExcelPath, $"Excel_{DateTime.Now:yyyyMMdd_HHmmss}_{Guid.NewGuid()}.xlsx");}using (var package = new ExcelPackage(filePath)){foreach (var sheetData in excelData){WriteSheetToPackage(sheetData.Key, sheetData.Value, package);}package.Save();}}private static void WriteSheetToPackage(string sheetName, List<ExcelRowData> rows, ExcelPackage package){if (string.IsNullOrWhiteSpace(sheetName))throw new ArgumentException("工作表名稱不能為空", nameof(sheetName));if (rows == null || rows.Count == 0)throw new ArgumentException("數據不能為空", nameof(rows));var ws = package.Workbook.Worksheets.Add(sheetName);// 寫表頭var headers = rows[0].Data.Keys.ToList();for (int col = 0; col < headers.Count; col++){ws.Cells[1, col + 1].Value = headers[col];}// 寫數據行for (int rowIndex = 0; rowIndex < rows.Count; rowIndex++){var rowData = rows[rowIndex].Data;int excelRow = rowIndex + 2;int colIndex = 1;foreach (var header in headers){rowData.TryGetValue(header, out string cellValue);ws.Cells[excelRow, colIndex].Value = cellValue;colIndex++;}}}#endregion#endregion