2018年9月9日 星期日

EPPlus Excel好用工具

介紹一個在C#中Excel好用的工具叫做EPPlus,可以產出Excel 或是讀取Excel到資料庫,語法簡潔好用,EPPluse適用Office 2007&2010,以下是簡單的範例。



先到NuGet套件管理員下載安裝EPPlus

  1. using OfficeOpenXml;
  2. using OfficeOpenXml.Style;
  3. using System.Drawing;
  4. using System.IO;
  5.  
  6. namespace EPPlusDemo
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. //檔案路徑
  13. string filePath = @"C:\csharp\ExcelTest.xlsx";
  14. //檢查檔案是否存在,存在則刪除
  15. if (File.Exists(filePath))
  16. {
  17. File.Delete(filePath);
  18. }
  19.  
  20. //建立ExcelPackge物件
  21. using (ExcelPackage p = new ExcelPackage())
  22. {
  23. //建立test1工作表
  24. ExcelWorksheet sheet = p.Workbook.Worksheets.Add("test1");
  25. //用Row Col表示位置
  26. sheet.Cells[1, 1].Value = "標題一";
  27. //用Excel欄位表示位置
  28. sheet.Cells["B1"].Value = "欄位二";
  29. for (int i = 3; i <= 5; i++)
  30. {
  31. //From Row,From Col,ToRow,To Col表示範圍
  32. sheet.Cells[1, 3, 1, 5].Value = "欄位" + i;
  33. }
  34.  
  35. //寫值
  36. for (int i = 2; i <= 5; i++)
  37. {
  38. for (int j = 1; j <= 5; j++)
  39. {
  40. sheet.Cells[i, j].Value = $"[{i},{j}]";
  41. }
  42. }
  43.  
  44. //設定框線
  45. sheet.Cells[1, 1, 5, 5].Style.Border.Top.Style = ExcelBorderStyle.Thin;
  46. sheet.Cells[1, 1, 5, 5].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
  47. sheet.Cells[1, 1, 5, 5].Style.Border.Left.Style = ExcelBorderStyle.Thin;
  48. sheet.Cells[1, 1, 5, 5].Style.Border.Right.Style = ExcelBorderStyle.Thin;
  49. //標題背景顏色
  50. ExcelRange header = sheet.Cells["A1:E1"];
  51. header.Style.Fill.PatternType = ExcelFillStyle.Solid;
  52. header.Style.Fill.BackgroundColor.SetColor(Color.LightGreen);
  53.  
  54. using (FileStream fileOutput = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
  55. {
  56. //存檔
  57. p.SaveAs(fileOutput);
  58. }
  59. }
  60. }
  61. }
  62. }

除了框線與顏色設定外,可設定的項目還有很多,例如合併儲存格,字型,輸入公式等等。
附上EPPlus官網


沒有留言:

張貼留言

EPPlus Excel好用工具