在ASP.NET Core中使用EPPlus匯入出Excel檔案
這篇文章說明了如何使用EPPlus在ASP.NET Core中匯入和匯出.xls/.xlsx檔案(Excel)。 在考慮使用.NET處理excel時,我們總是尋找第三方庫或元件。 使用Open Office Xml格式(xlsx)讀取和寫入Excel 2007/2010檔案的最流行的.net庫之一是 EPPlus 。這個庫現在已經支援.NET Core許久了 。 這適用於Windows,Linux和Mac。
因此,讓我們建立一個新的ASP.NET Core WEB API應用程式並安裝EPPlus.Core。 要安裝EPPlus.Core,請在程式包管理器控制檯中執行以下命令:
PM->Install-Package EPPlus.Core
或者您可以通過UI介面來安裝它.
一切就緒,現在建立一個控制器,命名為: ImportExportController ,新增後,讓我們編寫匯出方法。
為了方便演示,我在wwwroot資料夾中建立了一個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;
[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”。 當你開啟它時,你應該看到以下內容。
您還可以對標題進行加粗,這些並不是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); }
關於匯入,其實真實的情況還是比較複雜的,我們這裡就不進行驗證了,對於演示,我們只是讀取剛剛儲存的檔案。 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; } }
希望可以幫助到你。