使用「EPPLUS」讀取、產生 Excel

一、介紹

EPPLUS 是 .net 下的建立、修改、讀取 Excel 電子表格的套件。

二、開發工具

  • 整合開發環境:Visual Studio 2019
  • 語言:C#
  • .net framework:4.8

三、Nuget

EPPlus 4.5.3.3 最後 LGPL 授權的版本,商業利用可使用 4.5.3.3 版以下的版本。

  • Nuget:EPPlus
  • 版本:4.5.3.3

四、建立 Excel

範例原始碼是建置在 .net 的 MVC 的架構下。

範例 原始碼(c#)

public class EpplusController : Controller
{
    [HttpGet]
    public FileContentResult CreateExcel()
    {
        using (var ms = new MemoryStream())
        using (var ep = new ExcelPackage(ms))
        {
            var ws = ep.Workbook.Worksheets.Add("text");

            ws.Cells[1, 1].Value = "a1";
            ws.Cells[1, 2].Value = "a2";

            ws.Cells[2, 1].Value = "1";
            ws.Cells[2, 2].Value = "2";

            ep.SaveAs(ms);

            return File(ms.ToArray(), "application/octet-stream", "create.xlsx");
        }
    }
}

操作步驟

圖、執行 IIS Express

圖、輸入網址 https://你的網址/Epplus/CreateExcel, 即可下載 建立的 Excel

五、讀取 Excel

範例原始碼是建置在 .net 的 Web Api 的架構下。

範例 原始碼(c#)

public class EpplusController : ApiController
{
    [HttpGet]
    public List<Dictionary<object, object>> ReadExcel()
    {
        var ret = new List<Dictionary<object, object>>();

        var filePath = HostingEnvironment.MapPath("~/Template/read.xlsx");

        using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (var ep = new ExcelPackage(fs))
        {
            var sheet = ep.Workbook.Worksheets[1];
            var row = sheet.Dimension.End.Row;
            var col = sheet.Dimension.End.Column;

            for (var r = 2; r <= row; r++) {

                var dic = new Dictionary<object, object>();

                for (var i = 1; i <= col; i++) {
                    var v = sheet.Cells[1, i].Value;
                    dic[v] = sheet.Cells[r, i].Value;
                }

                ret.Add(dic);
            }
        }

        return ret;
    }
}

範例 Excel

圖、範例 Excel

操作步驟

圖、執行 IIS Express

圖、輸入網址 https://你的網址/api/Epplus/ReadExcel,即可看到讀取結果

六、參考

  1. EPPlus
  2. 使用「Visual Studio 2019」建置一個有 Mvc 和 Web Api 架構的網站

留言

這個網誌中的熱門文章

使用「LINE Messaging API」發送 line 訊息

使用「Visual Studio 2019」建置 Windows 服務

使用「NLog」來記錄應用程式的大小事吧

「Katalon Recorder」簡化測試腳本撰寫的工具

「linqkit」動態組裝 LINQ 條件的好用套件

使用 Visual Studio 2019 實作「RESTful API」

如何傳送訊息至「Teams」的 Channel

asp.net 下的 JSON 套件最佳利器「Newtonsoft.Json」

「Chrome Headless」隱藏瀏覽器的介面,讓爬蟲程式偷偷的執行