ASP.NET Core 匯入匯出Excel xlsx 檔案

來源:互聯網
上載者:User

標籤:put   www   命令列   mfile   office   line   程式   view   添加   

ASP.NET Core 使用EPPlus.Core匯入匯出Excel xlsx 檔案,EPPlus.Core支援Excel 2007/2010 xlsx檔案匯入匯出,可以運行在Windows, Linux和Mac。

EPPlus.Core 是基於EPPlus 更改而來,在Linux 下需要安裝libgdiplus 。

EPPlus:http://epplus.codeplex.com/

EPPlus.Core:https://github.com/VahidN/EPPlus.Core

下面在ASP.NET Core 中匯入匯出Excel xlsx 檔案。

建立項目

建立一個ASP.NET Core Web Application 項目ASPNETCoreExcel,選擇Web 應用程式 不進行身分識別驗證。

然後添加EPPlus.Core 引用。

使用NuGet 命令列:

Install-Package EPPlus.Core

也可以使用NuGet包管理器安裝。

匯出xlsx檔案

建立一個XlsxController ,添加Export 操作。

    public class XlsxController : Controller    {        private IHostingEnvironment _hostingEnvironment;        public XlsxController(IHostingEnvironment hostingEnvironment)        {            _hostingEnvironment = hostingEnvironment;        }        public IActionResult Index()        {            return View();        }        public IActionResult Export()        {            string sWebRootFolder = _hostingEnvironment.WebRootPath;            string sFileName = $"{Guid.NewGuid()}.xlsx";            FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));            using (ExcelPackage package = new ExcelPackage(file))            {                // 添加worksheet                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("aspnetcore");                //添加頭                worksheet.Cells[1, 1].Value = "ID";                worksheet.Cells[1, 2].Value = "Name";                worksheet.Cells[1, 3].Value = "Url";                //添加值                worksheet.Cells["A2"].Value = 1000;                worksheet.Cells["B2"].Value = "LineZero";                worksheet.Cells["C2"].Value = "http://www.cnblogs.com/linezero/";                worksheet.Cells["A3"].Value = 1001;                worksheet.Cells["B3"].Value = "LineZero GitHub";                worksheet.Cells["C3"].Value = "https://github.com/linezero";                worksheet.Cells["C3"].Style.Font.Bold = true;                package.Save();             }            return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");        }    }

 

通過依賴注入擷取HostingEnvironment,對應可以擷取程式的相關目錄及屬性。

然後添加Index 視圖增加一個連結匯出Excel

@{ }<h2>ASP.NET Core 匯入匯出Excel xlsx 檔案</h2><a asp-action="Export">匯出Excel</a>

點擊匯出檔案,開啟結果如下。

 

匯入xlsx檔案

在index視圖中添加一個上傳檔案,添加Import操作。

Index.cshtml

@{ }<h2>ASP.NET Core 匯入匯出Excel xlsx 檔案</h2><a asp-action="Export">匯出Excel</a><hr /><form enctype="multipart/form-data" method="post" asp-action="Import">    <input type="file" name="excelfile" />    <input type="submit" value="上傳" /></form>

 

        [HttpPost]        public IActionResult Import(IFormFile excelfile)        {            string sWebRootFolder = _hostingEnvironment.WebRootPath;            string sFileName = $"{Guid.NewGuid()}.xlsx";            FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));            try            {                using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))                {                    excelfile.CopyTo(fs);                    fs.Flush();                }                using (ExcelPackage package = new ExcelPackage(file))                {                    StringBuilder sb = new StringBuilder();                    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];                    int rowCount = worksheet.Dimension.Rows;                    int ColCount = worksheet.Dimension.Columns;                    bool bHeaderRow = true;                    for (int row = 1; row <= rowCount; row++)                    {                        for (int col = 1; col <= ColCount; col++)                        {                            if (bHeaderRow)                            {                                sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");                            }                            else                            {                                sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");                            }                        }                        sb.Append(Environment.NewLine);                    }                    return Content(sb.ToString());                }            }            catch (Exception ex)            {                return Content(ex.Message);            }        }

 

運行程式開啟http://localhost:5000/xlsx

 

 

 

 上傳對應檔案,顯示如下。

 

ASP.NET Core簡單的匯入匯出Excel 功能也就完成了。

 

如果你覺得本文對你有協助,請點擊“推薦”,謝謝。

 

ASP.NET Core 匯入匯出Excel xlsx 檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.