在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;
}
}

希望可以幫助到你。

