我的數據表結構:

1.編寫從數據庫讀取數據的相關業務邏輯(省略,若對我的業務邏輯代碼感興趣,可私聊)
2.編寫導出到excel表的代碼
控制器部分代碼如下:
/// <summary>
/// 導出數據
/// </summary>
/// <returns></returns>
[Route("ExportData")]
public IActionResult ExportData()
{
//TODO 從數據庫讀取數據相關業務邏輯需要自己編寫
var data = lawyerLogic.GetLawyers()?.ToList();
if (data?.Any() != true)
{
return new ContentResult() {Content = "未查詢到任何數據"};
}
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var ep = new ExcelPackage())
{
using (var worksheet = ep.Workbook.Worksheets.Add("導出數據測試"))
{
var x = 1;
var y = 1;
var columnTitles = new List<string>()
{
"律師編號",
"律師名稱",
"狀態"
};
foreach (var columnTitle in columnTitles)
{
var cell = worksheet.Cells[x, y++];
cell.Style.Font.Bold = true;
cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
cell.Value = columnTitle;
}
foreach (var item in data)
{
x++;
y = 1;
var cell = worksheet.Cells[x, y++];
cell.Value = item.LawyerId;
cell = worksheet.Cells[x, y++];
cell.Value = item.LawyerName;
cell = worksheet.Cells[x, y++];
cell.Value = (int)item.Status;
}
using (var stream = new MemoryStream())
{
ep.SaveAs(stream);
return new FileContentResult(stream.ToArray(),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName="導出數據測試.xlsx"
};
}
}
}
}
以上便是我的.net core3.1 從數據庫讀取數據(導出)到excel表過程及代碼,若有不足之處請指正,謝謝。
