這篇文章說明了如何使用EPPlus在ASP.NET Core中導入和導出.xls/.xlsx文件(Excel)。在考慮使用.NET處理excel時,咱們老是尋找第三方庫或組件。使用Open Office Xml格式(xlsx)讀取和寫入Excel 2007/2010文件的最流行的.net庫之一是EPPlus。這個庫如今已經支持.NET Core許久了。這適用於Windows,Linux和Mac。api
所以,讓咱們建立一個新的ASP.NET Core WEB API應用程序並安裝EPPlus.Core。要安裝EPPlus.Core,請在程序包管理器控制檯中運行如下命令:ui
PM->Install-Package EPPlus.Core
或者您能夠經過UI界面來安裝它.spa
一切就緒,如今建立一個控制器,命名爲: ImportExportController ,添加後,讓咱們編寫導出方法。.net
爲了方便演示,我在wwwroot文件夾中建立了一個excel文件,因此咱們就須要去獲取咱們的項目的絕對路徑。excel
public class ImportExportController : ControllerBase { private readonly IHostingEnvironment _hostingEnvironment; public ImportExportController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } }
ExcelPackage 在 OfficeOpenXml 命名空間中可用的類將用於讀寫xlsx。定義名爲「Export」的新Web api操做方法,該方法返回生成的xlsx文件的URL。因此這是將數據導出到xlsx的完整代碼。其中您須要 using OfficeOpenXml; code
[HttpGet] public string Export() { string sWebRootFolder = _hostingEnvironment.WebRootPath; string sFileName = @"demo.xlsx"; string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName); FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); if (file.Exists) { file.Delete(); file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); } using (ExcelPackage package = new ExcelPackage(file)) { // add a new worksheet to the empty workbook ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee"); //First add the headers worksheet.Cells[1, 1].Value = "ID"; worksheet.Cells[1, 2].Value = "Name"; worksheet.Cells[1, 3].Value = "Gender"; worksheet.Cells[1, 4].Value = "Salary (in $)"; //Add values worksheet.Cells["A2"].Value = 1000; worksheet.Cells["B2"].Value = "Jon"; worksheet.Cells["C2"].Value = "M"; worksheet.Cells["D2"].Value = 5000; worksheet.Cells["A3"].Value = 1001; worksheet.Cells["B3"].Value = "Graham"; worksheet.Cells["C3"].Value = "M"; worksheet.Cells["D3"].Value = 10000; worksheet.Cells["A4"].Value = 1002; worksheet.Cells["B4"].Value = "Jenny"; worksheet.Cells["C4"].Value = "F"; worksheet.Cells["D4"].Value = 5000; package.Save(); //Save the workbook. } return URL; }
就這樣。如今,當您運行此應用程序並調用export
方法時。完成後,訪問wwwroot
您的應用程序的文件夾。您應該在系統上看到「demo.xlsx」。當你打開它時,你應該看到如下內容。orm
您還能夠對標題進行加粗,這些並非EPPlus.Core給咱們提供的,你須要引用 using OfficeOpenXml; using OfficeOpenXml.Style; blog
using (var cells = worksheet.Cells[1, 1, 1, 4]) { cells.Style.Font.Bold = true; cells.Style.Fill.PatternType = ExcelFillStyle.Solid; cells.Style.Fill.BackgroundColor.SetColor(Color.LightGray); }
關於導入,其實真實的狀況仍是比較複雜的,咱們這裏就不進行驗證了,對於演示,咱們只是讀取剛剛保存的文件。 ImportAPI 將讀取文件並以格式化的字符串返回文件內容。如下是導入API的完整代碼,用於讀取xlsx,建立文件內容的格式化字符串並返回相同的內容。字符串
[HttpGet] [Route("Import")] public string Import() { string sWebRootFolder = _hostingEnvironment.WebRootPath; string sFileName = @"demo.xlsx"; FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); try { 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 sb.ToString(); } } catch (Exception ex) { return "Some error occured while importing." + ex.Message; } }
但願能夠幫助到你。get