ASP.NET Core中使用EPPlus導(dǎo)入出Excel文件的完整步驟
前言
這篇文章說明了如何使用EPPlus在ASP.NET Core中導(dǎo)入和導(dǎo)出.xls/.xlsx文件(Excel)。在考慮使用.NET處理excel時,我們總是尋找第三方庫或組件。使用Open Office Xml格式(xlsx)讀取和寫入Excel 2007/2010文件的最流行的.net庫之一是EPPlus。這個庫現(xiàn)在已經(jīng)支持.NET Core許久了。這適用于Windows,Linux和Mac。
因此,讓我們創(chuàng)建一個新的ASP.NET Core WEB API應(yīng)用程序并安裝EPPlus.Core。要安裝EPPlus.Core,請在程序包管理器控制臺中運行以下命令:
PM->Install-Package EPPlus.Core
或者您可以通過UI界面來安裝它.
一切就緒,現(xiàn)在創(chuàng)建一個控制器,命名為: ImportExportController ,添加后,讓我們編寫導(dǎo)出方法。
為了方便演示,我在wwwroot文件夾中創(chuàng)建了一個excel文件,所以我們就需要去獲取我們的項目的絕對路徑。
public class ImportExportController : ControllerBase { private readonly IHostingEnvironment _hostingEnvironment; public ImportExportController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } }
ExcelPackage 在 OfficeOpenXml 命名空間中可用的類將用于讀寫xlsx。定義名為“Export”的新Web api操作方法,該方法返回生成的xlsx文件的URL。所以這是將數(shù)據(jù)導(dǎo)出到xlsx的完整代碼。其中您需要 using OfficeOpenXml;
[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; }
就這樣?,F(xiàn)在,當(dāng)您運行此應(yīng)用程序并調(diào)用export方法時。完成后,訪問wwwroot您的應(yīng)用程序的文件夾。您應(yīng)該在系統(tǒng)上看到“demo.xlsx”。當(dāng)你打開它時,你應(yīng)該看到以下內(nèi)容。
您還可以對標(biāo)題進行加粗,這些并不是EPPlus.Core給我們提供的,你需要引用 using OfficeOpenXml; using OfficeOpenXml.Style;
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); }
關(guān)于導(dǎo)入,其實真實的情況還是比較復(fù)雜的,我們這里就不進行驗證了,對于演示,我們只是讀取剛剛保存的文件。 ImportAPI 將讀取文件并以格式化的字符串返回文件內(nèi)容。以下是導(dǎo)入API的完整代碼,用于讀取xlsx,創(chuàng)建文件內(nèi)容的格式化字符串并返回相同的內(nèi)容。
[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; } }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
C# 動態(tài)編譯、動態(tài)執(zhí)行、動態(tài)調(diào)試
前幾天看到一篇關(guān)于.net動態(tài)編譯的文章 .NET中的動態(tài)編譯 ,很受啟發(fā)。2009-05-05c# 連接字符串?dāng)?shù)據(jù)庫服務(wù)器端口號 .net狀態(tài)服務(wù)器端口號
正常的數(shù)據(jù)庫連接字符串配置,這是在MSSQL服務(wù)器端口是1433(默認(rèn))的情況下。2009-06-06.NET Core/Framework如何創(chuàng)建委托大幅度提高反射調(diào)用的性能詳解
反射是一種很重要的技術(shù),下面這篇文章主要給大家介紹了關(guān)于.NET Core/Framework如何創(chuàng)建委托大幅度提高反射調(diào)用性能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-09-09