[C#] .Net 下操作 Excel 新選擇 EPPlus - 建立 Excel 檔案,讀取 Excel ,寫入公式,計算公式讀取公式

2024-02-15

上次處理 Excel 問題還再 .Net Framewok ( 2014),現在都已經 .Net 8 了,該是時候找找看新的選擇,之前寫的 NPOI 當然都還可以使用

只是再想都已經到了 .Net8  有沒有其他好用的選擇 ,大概看了一下選了幾套測試,今天測試一下 EPPlus 


這邊解釋一下範例,基本上就是,第一個 Row 就是標題,接下來就是下面的資料,其中有一個薪水的欄位

我會在下面進行加總的測試,也就是可以寫入公式,並且執行計算結果


EPPlus Create Excel and Formula Example: 

var excelPackage = new ExcelPackage(); var worksheet = excelPackage.Workbook.Worksheets.Add("試算表1"); worksheet.Cells[1, 1].Value = "員工編號"; worksheet.Cells[1, 2].Value = "姓名"; worksheet.Cells[1, 3].Value = "到值日"; worksheet.Cells[1, 4].Value = "電話"; worksheet.Cells[1, 5].Value = "薪水"; worksheet.Cells[2, 1].Value = "NO001"; worksheet.Cells[2, 2].Value = "Donma Hsu"; worksheet.Cells[2, 3].Value = "2023/01/09"; worksheet.Cells[2, 4].Value = "09123456789"; worksheet.Cells[2, 5].Value = 999_999m; worksheet.Cells[3, 1].Value = "NO002"; worksheet.Cells[3, 2].Value = "Kelly Chen"; worksheet.Cells[3, 3].Value = "2023/01/10"; worksheet.Cells[3, 4].Value = "09987654321"; worksheet.Cells[3, 5].Value = 666_666m; //設定為粗體 worksheet.Cells["A1:E1"].Style.Font.Bold = true; //套入公式算總合 worksheet.Cells[4, 5].Formula = string.Format("SUM(E2,E3)"); worksheet.Calculate(); excelPackage.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "sample1.xlsx");


結果:


Read Data and Get Formula from Excel File.

var excelPackage = new ExcelPackage(AppDomain.CurrentDomain.BaseDirectory + "sample1.xlsx"); var worksheet = excelPackage.Workbook.Worksheets[0]; var data = worksheet.GetValue(4, 5); //讀取計算結果 Console.WriteLine("Calc Value :" + data); //讀取公式 Console.WriteLine("公式 :" + worksheet.Cells[4,5].Formula);


整體來說,操作比 NPOI 簡單一些,但是記得他是從1,1 當作起始座標起點,寫程式比較習慣是從 0 開始,但是這是從 1,1 

先記錄一下之後有一些其他操作心得再補上



當麻許的碎念筆記 2014 | Donma Hsu Design.