ASP.NET Core導入導出Excel文件
希望在ASP.NET Core中導入導出Excel文件,在網上搜了一遍,基本都是使用EPPlus插件,EPPlus挺好用,但商用需要授權,各位碼友若有好的工具包推薦,請給我留言,謝謝!
本文利用Asp.net core Razor頁面實現Excel文件的導入導出,參考大神的文章:ASP.NET Core 導入導出Excel xlsx 文件 - LineZero - 博客園 (cnblogs.com)
下面為詳細步驟。
1,創建Razor項目
2,在Nuget包管理器中搜索EPPlus, 安裝依賴包。EPPlus.Core已經棄用,EPPlus是支持Net Core的最新版本。
3,修改pages/Index.cshtml文件,創建基本導入導出頁面。
@page @model IndexModel @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1 class="display-4">ASP.NET Core導入導出Excel文件</h1> </div> <h2></h2> <hr /> <div> <h4>導入Excel</h4> <hr /> <form enctype="multipart/form-data" method="post" asp-page-handler="Import"> <input type="file" name="excelFile"/> <input type="submit" value="導入"/> </form> <hr /> </div> <hr /> <div> <h4>導出Excel</h4> <form enctype="multipart/form-data" method="post"asp-page-handler="Export"> <input type="submit" value="導出"/> </form> </div> <hr />
4,修改Index.cshtml.cs文件中的代碼,增加OnPostImport 和OnPostExport方法,分別用於導入、導出文件。
首先在構造函數中注入webHostEnvironment
private readonly IWebHostEnvironment _webHostEnvironment; public IndexModel(IWebHostEnvironment webHostEnvironment) { _webHostEnvironment = webHostEnvironment; }
OnPostImport代碼:
public IActionResult OnPostImport(IFormFile excelFile) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; string sWebRootFolder = _webHostEnvironment.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[0]; 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) { if(worksheet.Cells[row, col].Value != null) { sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t"); } else { sb.Append("\t"); } } else { if(worksheet.Cells[row, col].Value != null) { sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t"); } else { sb.Append("\t"); } } } sb.Append(Environment.NewLine); if (bheaderRow) { sb.Append("-----------------------------------------"); sb.Append(Environment.NewLine); } bheaderRow = false; } return Content(sb.ToString()); } } catch(Exception ex) { return Content(ex.Message); } }
其中必須添加
ExcelPackage.LicenseContext = LicenseContext.NonCommercial 用於指定EPPlus的使用授權為非商用。缺少會報錯。
OnPostExport代碼:
public IActionResult OnPostExport() { string sWebRootFolder = _webHostEnvironment.WebRootPath; string sFileName = $"{Guid.NewGuid()}.xlsx"; FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (ExcelPackage package=new ExcelPackage(file)) { //add worksheet ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("AspNetCore"); //add table header workSheet.Cells[1, 1].Value = "ID"; workSheet.Cells[1, 2].Value = "Name"; workSheet.Cells[1, 3].Value = "Gender"; workSheet.Cells[1, 4].Value = "Age"; workSheet.Cells[1, 5].Value = "Remark"; //Add value workSheet.Cells["A2"].Value = 1000; workSheet.Cells["B2"].Value = "張三"; workSheet.Cells["C2"].Value = "男"; workSheet.Cells["D2"].Value = 25; workSheet.Cells["E2"].Value = "ABCD"; workSheet.Cells["A3"].Value = 1001; workSheet.Cells["B3"].Value = "李四"; workSheet.Cells["C3"].Value = "女"; workSheet.Cells["D3"].Value = 35; workSheet.Cells["D3"].Style.Font.Bold = true; workSheet.Cells["A4"].Value = 1003; workSheet.Cells["B4"].Value = "Amy"; workSheet.Cells["C4"].Value = "Female"; workSheet.Cells["D4"].Value = 22; workSheet.Cells["E4"].Value = "Hello world"; workSheet.Cells["A5"].Value = 1004; workSheet.Cells["B5"].Value = "Jim"; workSheet.Cells["C5"].Value = "Male"; workSheet.Cells["D5"].Value = 35; workSheet.Cells["E5"].Value = 500; package.Save(); } return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); }
Index.cshtml.cs的完整代碼如下:
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using OfficeOpenXml; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using WebAppTest.Models; namespace WebAppTest.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; private readonly IWebHostEnvironment _webHostEnvironment; public IndexModel(ILogger<IndexModel> logger,IWebHostEnvironment webHostEnvironment) { _logger = logger; _context = context; _webHostEnvironment = webHostEnvironment; } public void OnGet() { } public IActionResult OnPostImport(IFormFile excelFile) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; string sWebRootFolder = _webHostEnvironment.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[0]; 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) { if(worksheet.Cells[row, col].Value != null) { sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t"); } else { sb.Append("\t"); } } else { if(worksheet.Cells[row, col].Value != null) { sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t"); } else { sb.Append("\t"); } } } sb.Append(Environment.NewLine); if (bheaderRow) { sb.Append("-----------------------------------------"); sb.Append(Environment.NewLine); } bheaderRow = false; } return Content(sb.ToString()); } } catch(Exception ex) { return Content(ex.Message); } } public IActionResult OnPostExport() { string sWebRootFolder = _webHostEnvironment.WebRootPath; string sFileName = $"{Guid.NewGuid()}.xlsx"; FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (ExcelPackage package=new ExcelPackage(file)) { //add worksheet ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("AspNetCore"); //add table header workSheet.Cells[1, 1].Value = "ID"; workSheet.Cells[1, 2].Value = "Name"; workSheet.Cells[1, 3].Value = "Gender"; workSheet.Cells[1, 4].Value = "Age"; workSheet.Cells[1, 5].Value = "Remark"; //Add value workSheet.Cells["A2"].Value = 1000; workSheet.Cells["B2"].Value = "張三"; workSheet.Cells["C2"].Value = "男"; workSheet.Cells["D2"].Value = 25; workSheet.Cells["E2"].Value = "ABCD"; workSheet.Cells["A3"].Value = 1001; workSheet.Cells["B3"].Value = "李四"; workSheet.Cells["C3"].Value = "女"; workSheet.Cells["D3"].Value = 35; workSheet.Cells["D3"].Style.Font.Bold = true; workSheet.Cells["A4"].Value = 1003; workSheet.Cells["B4"].Value = "Amy"; workSheet.Cells["C4"].Value = "Female"; workSheet.Cells["D4"].Value = 22; workSheet.Cells["E4"].Value = "Hello world"; workSheet.Cells["A5"].Value = 1004; workSheet.Cells["B5"].Value = "Jim"; workSheet.Cells["C5"].Value = "Male"; workSheet.Cells["D5"].Value = 35; workSheet.Cells["E5"].Value = 500; package.Save(); } return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); } } }
5,運行項目,測試導入導出功能。
導出功能,單擊導出按鈕,瀏覽器會下載excel文件,
導入功能,點擊選擇文件按鈕,選擇剛下載的excel文件,點擊導入按鈕,跳轉到導入結果頁面。
------------------------ 完成---------------------